Improved bbcache and documented it.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent f40c884 · Browse files · 6 files·+194 added−78 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+194 added−78 removed
- other:+194 added−78 removed
Provenance
- Commit
a816bf4- Tree
7aa629b- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
f40c884
6 files changed+194 added−78 removed
modified:docs/api.rst+62 added-22 removed
248 unmodified lines249 250 The closest to regular Python behavior is the `StrictUndefined` which251 disallows all operations beside testing if it's an undefined object.252 253-.. autoclass:: jinja2.runtime.Undefined()253+.. autoclass:: jinja2.Undefined()254 255 .. attribute:: _undefined_hint256 257 Either `None` or an unicode string with the error message for19 unmodified lines277 When called with any arguments this method raises278 :attr:`_undefined_exception` with an error message generated279 from the undefined hints stored on the undefined object.280 281-.. autoclass:: jinja2.runtime.DebugUndefined()281+.. autoclass:: jinja2.DebugUndefined()282 283-.. autoclass:: jinja2.runtime.StrictUndefined()283+.. autoclass:: jinja2.StrictUndefined()284 285 Undefined objects are created by calling :attr:`undefined`.286 287 .. admonition:: Implementation90 unmodified lines378 size by default and templates are automatically reloaded.379 All loaders are subclasses of :class:`BaseLoader`. If you want to create your380 own loader, subclass :class:`BaseLoader` and override `get_source`.381 382-.. autoclass:: jinja2.loaders.BaseLoader382+.. autoclass:: jinja2.BaseLoader383 :members: get_source, load384 385 Here a list of the builtin loaders Jinja2 provides:386 387-.. autoclass:: jinja2.loaders.FileSystemLoader387+.. autoclass:: jinja2.FileSystemLoader388 389-.. autoclass:: jinja2.loaders.PackageLoader389+.. autoclass:: jinja2.PackageLoader390 391-.. autoclass:: jinja2.loaders.DictLoader391+.. autoclass:: jinja2.DictLoader392 393-.. autoclass:: jinja2.loaders.FunctionLoader393+.. autoclass:: jinja2.FunctionLoader394 395-.. autoclass:: jinja2.loaders.PrefixLoader395+.. autoclass:: jinja2.PrefixLoader396 397-.. autoclass:: jinja2.loaders.ChoiceLoader397+.. autoclass:: jinja2.ChoiceLoader398 399 400+.. _bytecode-cache:401+402+Bytecode Cache403+--------------404+405+Jinja 2.1 and higher support external bytecode caching. Bytecode caches make406+it possible to store the generated bytecode on the file system or a different407+location to avoid parsing the templates on first use.408+409+This is especially useful if you have a web application that is initialized on410+the first request and Jinja compiles many templates at once which slows down411+the application.412+413+To use a bytecode cache, instanciate it and pass it to the :class:`Environment`.414+415+.. autoclass:: jinja2.BytecodeCache416+ :members: load_bytecode, dump_bytecode, clear417+418+.. autoclass:: jinja2.bccache.Bucket419+ :members: write_bytecode, load_bytecode, bytecode_from_string,420+ bytecode_to_string, reset421+422+ .. attribute:: environment423+424+ The :class:`Environment` that created the bucket.425+426+ .. attribute:: key427+428+ The unique cache key for this bucket429+430+ .. attribute:: code431+432+ The bytecode if it's loaded, otherwise `None`.433+434+435+Builtin bytecode caches:436+437+.. autoclass:: jinja2.FileSystemBytecodeCache438+439+440 Utilities441 ---------442 443 These helper functions and classes are useful if you add custom filters or444 functions to a Jinja2 environment.445 406-.. autofunction:: jinja2.filters.environmentfilter446+.. autofunction:: jinja2.environmentfilter447 408-.. autofunction:: jinja2.filters.contextfilter448+.. autofunction:: jinja2.contextfilter449 410-.. autofunction:: jinja2.utils.environmentfunction450+.. autofunction:: jinja2.environmentfunction451 412-.. autofunction:: jinja2.utils.contextfunction452+.. autofunction:: jinja2.contextfunction453 454 .. function:: escape(s)455 456 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`2 unmodified lines459 that do have an HTML representation such as already escaped data.460 461 The return value is a :class:`Markup` string.462 423-.. autofunction:: jinja2.utils.clear_caches463+.. autofunction:: jinja2.clear_caches464 425-.. autofunction:: jinja2.utils.is_undefined465+.. autofunction:: jinja2.is_undefined466 427-.. autoclass:: jinja2.utils.Markup([string])467+.. autoclass:: jinja2.Markup([string])468 :members: escape, unescape, striptags469 470 .. admonition:: Note471 4 unmodified lines476 477 Exceptions478 ----------479 440-.. autoexception:: jinja2.exceptions.TemplateError480+.. autoexception:: jinja2.TemplateError481 442-.. autoexception:: jinja2.exceptions.UndefinedError482+.. autoexception:: jinja2.UndefinedError483 444-.. autoexception:: jinja2.exceptions.TemplateNotFound484+.. autoexception:: jinja2.TemplateNotFound485 446-.. autoexception:: jinja2.exceptions.TemplateSyntaxError486+.. autoexception:: jinja2.TemplateSyntaxError487 488 .. attribute:: message489 490 The error message as utf-8 bytestring.14 unmodified lines505 The reason why the filename and error message are bytestrings and not506 unicode strings is that Python 2.x is not using unicode for exceptions507 and tracebacks as well as the compiler. This will change with Python 3.508 469-.. autoexception:: jinja2.exceptions.TemplateAssertionError509+.. autoexception:: jinja2.TemplateAssertionError510 511 512 .. _writing-filters:513 152 unmodified linesmodified:jinja2/__init__.py+3 added
38 unmodified lines39 # loaders40 from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \41 DictLoader, FunctionLoader, PrefixLoader, ChoiceLoader42 43+# bytecode caches44+from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache45+46 # undefined types47 from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined48 49 # exceptions17 unmodified linesmodified:jinja2/bccache.py+109 added-50 removed
12 unmodified lines13 14 :copyright: Copyright 2008 by Armin Ronacher.15 :license: BSD.16 """17-from os import path17+from os import path, listdir, remove18 import marshal19+import tempfile20 import cPickle as pickle21+import fnmatch22 from cStringIO import StringIO23 try:24 from hashlib import sha125 except ImportError:4 unmodified lines30 bc_magic = 'j2' + pickle.dumps(bc_version, 2)31 32 33 class Bucket(object):32- """Buckets are used to store the bytecode for one template. It's33- initialized by the bytecode cache with the checksum for the code34- as well as the unique key.34+ """Buckets are used to store the bytecode for one template. It's created35+ and initialized by the bytecode cache and passed to the loading functions.36 36- The bucket then provides method to load the bytecode from file(-like)37- objects and strings or dump it again.37+ The buckets get an internal checksum from the cache assigned and use this38+ to automatically reject outdated cache material. Individual bytecode39+ cache subclasses don't have to care about cache invalidation.40 """41 40- def __init__(self, cache, environment, key, checksum):41- self._cache = cache42+ def __init__(self, environment, key, checksum):43 self.environment = environment44 self.key = key45 self.checksum = checksum46 self.reset()47 48 def reset(self):48- """Resets the bucket (unloads the code)."""49+ """Resets the bucket (unloads the bytecode)."""50 self.code = None51 51- def load(self, f):52- """Loads bytecode from a f."""52+ def load_bytecode(self, f):53+ """Loads bytecode from a file or file like object."""54 # make sure the magic header is correct55 magic = f.read(len(bc_magic))56 if magic != bc_magic:57 self.reset()58 return59 # the source code of the file changed, we need to reload59- checksum = pickle.load(f)60+ checksum = pickle.load_bytecode(f)61 if self.checksum != checksum:62 self.reset()63 return63- # now load the code. Because marshal is not able to load64+ # now load_bytecode the code. Because marshal is not able to load_bytecode65 # from arbitrary streams we have to work around that66 if isinstance(f, file):66- self.code = marshal.load(f)67+ self.code = marshal.load_bytecode(f)68 else:69 self.code = marshal.loads(f.read())70 70- def dump(self, f):71- """Dump the bytecode into f."""71+ def write_bytecode(self, f):72+ """Dump the bytecode into the file or file like object passed."""73 if self.code is None:74 raise TypeError('can\'t write empty bucket')75 f.write(bc_magic)75- pickle.dump(self.checksum, f, 2)76+ pickle.write_bytecode(self.checksum, f, 2)77 if isinstance(f, file):77- marshal.dump(self.code, f)78+ marshal.write_bytecode(self.code, f)79 else:80 f.write(marshal.dumps(self.code))81 81- def loads(self, string):82+ def bytecode_from_string(self, string):83 """Load bytecode from a string."""83- self.load(StringIO(string))84+ self.load_bytecode(StringIO(string))85 85- def dumps(self):86+ def bytecode_to_string(self):87 """Return the bytecode as string."""88 out = StringIO()88- self.dump(out)89+ self.write_bytecode(out)90 return out.getvalue()91 91- def write_back(self):92- """Write the bucket back to the cache."""93- self._cache.dump_bucket(self)92 95-93 class BytecodeCache(object):94 """To implement your own bytecode cache you have to subclass this class98- and override :meth:`load_bucket` and :meth:`dump_bucket`. Both of these99- methods are passed a :class:`Bucket` that they have to load or dump.95+ and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of96+ these methods are passed a :class:`~jinja2.bccache.Bucket`.97+98+ A very basic bytecode cache that saves the bytecode on the file system::99+100+ from os import path101+102+ class MyCache(BytecodeCache):103+104+ def __init__(self, directory):105+ self.directory = directory106+107+ def load_bytecode(self, bucket):108+ filename = path.join(self.directory, bucket.key)109+ if path.exists(filename):110+ with file(filename, 'rb') as f:111+ bucket.load_bytecode(f)112+113+ def dump_bytecode(self, bucket):114+ filename = path.join(self.directory, bucket.key)115+ with file(filename, 'wb') as f:116+ bucket.write_bytecode(f)117+118+ A more advanced version of a filesystem based bytecode cache is part of119+ Jinja2.120 """121 102- def load_bucket(self, bucket):103- """Subclasses have to override this method to load bytecode104- into a bucket.122+ def load_bytecode(self, bucket):123+ """Subclasses have to override this method to load bytecode into a124+ bucket. If they are not able to find code in the cache for the125+ bucket, it must not do anything.126 """127 raise NotImplementedError()128 108- def dump_bucket(self, bucket):109- """Subclasses have to override this method to write the110- bytecode from a bucket back to the cache.129+ def dump_bytecode(self, bucket):130+ """Subclasses have to override this method to write the bytecode131+ from a bucket back to the cache. If it unable to do so it must not132+ fail silently but raise an exception.133 """134 raise NotImplementedError()135 114- def get_cache_key(self, name):115- """Return the unique hash key for this template name."""116- return sha1(name.encode('utf-8')).hexdigest()136+ def clear(self):137+ """Clears the cache. This method is not used by Jinja2 but should be138+ implemented to allow applications to clear the bytecode cache used139+ by a particular environment.140+ """141 142+ def get_cache_key(self, name, filename=None):143+ """Returns the unique hash key for this template name."""144+ hash = sha1(name.encode('utf-8'))145+ if filename is not None:146+ if isinstance(filename, unicode):147+ filename = filename.encode('utf-8')148+ hash.update('|' + filename)149+ return hash.hexdigest()150+151 def get_source_checksum(self, source):119- """Return a checksum for the source."""152+ """Returns a checksum for the source."""153 return sha1(source.encode('utf-8')).hexdigest()154 122- def get_bucket(self, environment, name, source):123- """Return a cache bucket."""124- key = self.get_cache_key(name)155+ def get_bucket(self, environment, name, filename, source):156+ """Return a cache bucket for the given template. All arguments are157+ mandatory but filename may be `None`.158+ """159+ key = self.get_cache_key(name, filename)160 checksum = self.get_source_checksum(source)126- bucket = Bucket(self, environment, key, checksum)127- self.load_bucket(bucket)161+ bucket = Bucket(environment, key, checksum)162+ self.load_bytecode(bucket)163 return bucket164 165+ def set_bucket(self, bucket):166+ """Put the bucket into the cache."""167+ self.dump_bytecode(bucket)168 131-class FileSystemCache(BytecodeCache):132- """A bytecode cache that stores bytecode on the filesystem."""169 134- def __init__(self, directory, pattern='%s.jbc'):170+class FileSystemBytecodeCache(BytecodeCache):171+ """A bytecode cache that stores bytecode on the filesystem. It accepts172+ two arguments: The directory where the cache items are stored and a173+ pattern string that is used to build the filename.174+175+ If no directory is specified the system temporary items folder is used.176+177+ The pattern can be used to have multiple separate caches operate on the178+ same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``179+ is replaced with the cache key.180+181+ >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')182+ """183+184+ def __init__(self, directory=None, pattern='__jinja2_%s.cache'):185+ if directory is None:186+ directory = tempfile.gettempdir()187 self.directory = directory188 self.pattern = pattern189 190 def _get_cache_filename(self, bucket):191 return path.join(self.directory, self.pattern % bucket.key)192 141- def load_bucket(self, bucket):193+ def load_bytecode(self, bucket):194 filename = self._get_cache_filename(bucket)195 if path.exists(filename):196 f = file(filename, 'rb')197 try:146- bucket.load(f)198+ bucket.load_bytecode(f)199 finally:200 f.close()201 150- def dump_bucket(self, bucket):202+ def dump_bytecode(self, bucket):203 filename = self._get_cache_filename(bucket)204 f = file(filename, 'wb')205 try:154- bucket.dump(f)206+ bucket.write_bytecode(f)207 finally:208 f.close()209+210+ def clear(self):211+ for filename in filter(listdir(self.directory), self.pattern % '*'):212+ try:213+ remove(path.join(self.directory, filename))214+ except OSError:215+ passmodified:jinja2/environment.py+2 added
158 unmodified lines159 `bytecode_cache`160 If set to a bytecode cache object, this object will provide a161 cache for the internal Jinja bytecode so that templates don't162 have to be parsed if they were not changed.163+164+ See :ref:`bytecode-cache` for more information.165 """166 167 #: if this environment is sandboxed. Modifying this variable won't make168 #: the environment sandboxed though. For a real sandboxed environment594 unmodified linesmodified:jinja2/loaders.py+16 added-6 removed
84 unmodified lines85 override this method as loaders working on collections of other86 loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)87 will not call this method but `get_source` directly.88 """89+ code = None90 if globals is None:91 globals = {}92+93+ # first we try to get the source for this template together94+ # with the filename and the uptodate function.95 source, filename, uptodate = self.get_source(environment, name)96 93- code = bucket = None94- if environment.bytecode_cache is not None:95- bucket = environment.bytecode_cache.get_bucket(environment, name,96- source)97+ # try to load the code from the bytecode cache if there is a98+ # bytecode cache configured.99+ bbc = environment.bytecode_cache100+ if bbc is not None:101+ bucket = bcc.get_bucket(environment, name, filename, source)102 code = bucket.code103 104+ # if we don't have code so far (not cached, no longer up to105+ # date) etc. we compile the template106 if code is None:107 code = environment.compile(source, name, filename)108 109+ # if the bytecode cache is available and the bucket doesn't110+ # have a code so far, we give the bucket the new code and put111+ # it back to the bytecode cache.102- if bucket and bucket.code is None:112+ if bbc is not None and bucket.code is None:113 bucket.code = code104- bucket.write_back()114+ bbc.set_bucket(bucket)115 116 return environment.template_class.from_code(environment, code,117 globals, uptodate)118 181 unmodified linesmodified:CHANGES+2 added
28 unmodified lines29 - added `sort` filter that works like `dictsort` but for arbitrary sequences.30 31 - fixed a bug with empty statements in macros.32 33+- implemented a bytecode cache system. (:ref:`bytecode-cache`)34+35 Version 2.036 -----------37 (codename jinjavitus, released on July 17th 2008)38 32 unmodified lines