<s> from __future__ import unicode_literals <EOL> import hashlib <EOL> from django . template import Library , Node , TemplateSyntaxError , Variable , VariableDoesNotExist <EOL> from django . template import resolve_variable <EOL> from django . core . cache import cache <EOL> from django . utils . encoding import force_bytes <EOL> from django . utils . http import urlquote <EOL> register = Library ( ) <EOL> class CacheNode ( Node ) : <EOL> def __init__ ( self , nodelist , expire_time_var , fragment_name , vary_on ) : <EOL> self . nodelist = nodelist <EOL> self . expire_time_var = Variable ( expire_time_var ) <EOL> self . fragment_name = fragment_name <EOL> self . vary_on = vary_on <EOL> def render ( self , context ) : <EOL> try : <EOL> expire_time = self . expire_time_var . resolve ( context ) <EOL> except VariableDoesNotExist : <EOL> raise TemplateSyntaxError ( '<STR_LIT>' % self . expire_time_var . var ) <EOL> try : <EOL> expire_time = int ( expire_time ) <EOL> except ( ValueError , TypeError ) : <EOL> raise TemplateSyntaxError ( '<STR_LIT>' % expire_time ) <EOL> key = '<STR_LIT::>' . join ( [ urlquote ( resolve_variable ( var , context ) ) for var in self . vary_on ] ) <EOL> args = hashlib . md5 ( force_bytes ( key ) ) <EOL> cache_key = '<STR_LIT>' % ( self . fragment_name , args . hexdigest ( ) ) <EOL> value = cache . get ( cache_key ) <EOL> if value is None : <EOL> value = self . nodelist . render ( context ) <EOL> cache . set ( cache_key , value , expire_time ) <EOL> return value <EOL> @ register . tag ( '<STR_LIT>' ) <EOL> def do_cache ( parser , token ) : <EOL> """<STR_LIT>""" <EOL> nodelist = parser . parse ( ( '<STR_LIT>' , ) ) <EOL> parser . delete_first_token ( ) <EOL> tokens = token . contents . split ( ) <EOL> if len ( tokens ) < <NUM_LIT:3> : <EOL> raise TemplateSyntaxError ( "<STR_LIT>" % tokens [ <NUM_LIT:0> ] ) <EOL> return CacheNode ( nodelist , tokens [ <NUM_LIT:1> ] , tokens [ <NUM_LIT:2> ] , tokens [ <NUM_LIT:3> : ] ) </s>
