Skip to content
Myr

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

6 files+194 added−78 removed

modified:docs/api.rst+62 added-22 removed
248 unmodified lines
249250The closest to regular Python behavior is the `StrictUndefined` which251disallows all operations beside testing if it's an undefined object.252253.. autoclass:: jinja2.runtime.Undefined()253.. autoclass:: jinja2.Undefined()254255 .. attribute:: _undefined_hint256257 Either `None` or an unicode string with the error message for
19 unmodified lines
277 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.280281.. autoclass:: jinja2.runtime.DebugUndefined()281.. autoclass:: jinja2.DebugUndefined()282283.. autoclass:: jinja2.runtime.StrictUndefined()283.. autoclass:: jinja2.StrictUndefined()284285Undefined objects are created by calling :attr:`undefined`.286287.. admonition:: Implementation
90 unmodified lines
378size by default and templates are automatically reloaded.379All loaders are subclasses of :class:`BaseLoader`. If you want to create your380own loader, subclass :class:`BaseLoader` and override `get_source`.381382.. autoclass:: jinja2.loaders.BaseLoader382.. autoclass:: jinja2.BaseLoader383 :members: get_source, load384385Here a list of the builtin loaders Jinja2 provides:386387.. autoclass:: jinja2.loaders.FileSystemLoader387.. autoclass:: jinja2.FileSystemLoader388389.. autoclass:: jinja2.loaders.PackageLoader389.. autoclass:: jinja2.PackageLoader390391.. autoclass:: jinja2.loaders.DictLoader391.. autoclass:: jinja2.DictLoader392393.. autoclass:: jinja2.loaders.FunctionLoader393.. autoclass:: jinja2.FunctionLoader394395.. autoclass:: jinja2.loaders.PrefixLoader395.. autoclass:: jinja2.PrefixLoader396397.. autoclass:: jinja2.loaders.ChoiceLoader397.. autoclass:: jinja2.ChoiceLoader398399400.. _bytecode-cache:401402Bytecode Cache403--------------404405Jinja 2.1 and higher support external bytecode caching. Bytecode caches make406it possible to store the generated bytecode on the file system or a different407location to avoid parsing the templates on first use.408409This is especially useful if you have a web application that is initialized on410the first request and Jinja compiles many templates at once which slows down411the application.412413To use a bytecode cache, instanciate it and pass it to the :class:`Environment`.414415.. autoclass:: jinja2.BytecodeCache416 :members: load_bytecode, dump_bytecode, clear417418.. autoclass:: jinja2.bccache.Bucket419 :members: write_bytecode, load_bytecode, bytecode_from_string,420 bytecode_to_string, reset421422 .. attribute:: environment423424 The :class:`Environment` that created the bucket.425426 .. attribute:: key427428 The unique cache key for this bucket429430 .. attribute:: code431432 The bytecode if it's loaded, otherwise `None`.433434435Builtin bytecode caches:436437.. autoclass:: jinja2.FileSystemBytecodeCache438439440Utilities441---------442443These helper functions and classes are useful if you add custom filters or444functions to a Jinja2 environment.445406.. autofunction:: jinja2.filters.environmentfilter446.. autofunction:: jinja2.environmentfilter447408.. autofunction:: jinja2.filters.contextfilter448.. autofunction:: jinja2.contextfilter449410.. autofunction:: jinja2.utils.environmentfunction450.. autofunction:: jinja2.environmentfunction451412.. autofunction:: jinja2.utils.contextfunction452.. autofunction:: jinja2.contextfunction453454.. function:: escape(s)455456 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`
2 unmodified lines
459 that do have an HTML representation such as already escaped data.460461 The return value is a :class:`Markup` string.462423.. autofunction:: jinja2.utils.clear_caches463.. autofunction:: jinja2.clear_caches464425.. autofunction:: jinja2.utils.is_undefined465.. autofunction:: jinja2.is_undefined466427.. autoclass:: jinja2.utils.Markup([string])467.. autoclass:: jinja2.Markup([string])468 :members: escape, unescape, striptags469470.. admonition:: Note471
4 unmodified lines
476477Exceptions478----------479440.. autoexception:: jinja2.exceptions.TemplateError480.. autoexception:: jinja2.TemplateError481442.. autoexception:: jinja2.exceptions.UndefinedError482.. autoexception:: jinja2.UndefinedError483444.. autoexception:: jinja2.exceptions.TemplateNotFound484.. autoexception:: jinja2.TemplateNotFound485446.. autoexception:: jinja2.exceptions.TemplateSyntaxError486.. autoexception:: jinja2.TemplateSyntaxError487488 .. attribute:: message489490 The error message as utf-8 bytestring.
14 unmodified lines
505 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.508469.. autoexception:: jinja2.exceptions.TemplateAssertionError509.. autoexception:: jinja2.TemplateAssertionError510511512.. _writing-filters:513
152 unmodified lines
modified:jinja2/__init__.py+3 added
38 unmodified lines
39# loaders40from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \41 DictLoader, FunctionLoader, PrefixLoader, ChoiceLoader4243# bytecode caches44from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache4546# undefined types47from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined4849# exceptions
17 unmodified lines
modified:jinja2/bccache.py+109 added-50 removed
12 unmodified lines
1314 :copyright: Copyright 2008 by Armin Ronacher.15 :license: BSD.16"""17from os import path17from os import path, listdir, remove18import marshal19import tempfile20import cPickle as pickle21import fnmatch22from cStringIO import StringIO23try:24 from hashlib import sha125except ImportError:
4 unmodified lines
30bc_magic = 'j2' + pickle.dumps(bc_version, 2)313233class 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.3636 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 """4140 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()4748 def reset(self):48 """Resets the bucket (unloads the code)."""49 """Resets the bucket (unloads the bytecode)."""50 self.code = None5151 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())7070 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))8181 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))8585 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()9191 def write_back(self):92 """Write the bucket back to the cache."""93 self._cache.dump_bucket(self)929593class 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`.9798 A very basic bytecode cache that saves the bytecode on the file system::99100 from os import path101102 class MyCache(BytecodeCache):103104 def __init__(self, directory):105 self.directory = directory106107 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)112113 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)117118 A more advanced version of a filesystem based bytecode cache is part of119 Jinja2.120 """121102 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()128108 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()135114 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 """141142 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()150151 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()154122 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 bucket164165 def set_bucket(self, bucket):166 """Put the bucket into the cache."""167 self.dump_bytecode(bucket)168131class FileSystemCache(BytecodeCache):132 """A bytecode cache that stores bytecode on the filesystem."""169134 def __init__(self, directory, pattern='%s.jbc'):170class 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.174175 If no directory is specified the system temporary items folder is used.176177 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.180181 >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')182 """183184 def __init__(self, directory=None, pattern='__jinja2_%s.cache'):185 if directory is None:186 directory = tempfile.gettempdir()187 self.directory = directory188 self.pattern = pattern189190 def _get_cache_filename(self, bucket):191 return path.join(self.directory, self.pattern % bucket.key)192141 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()201150 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()209210 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 pass
modified:jinja2/environment.py+2 added
158 unmodified lines
159 `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.163164 See :ref:`bytecode-cache` for more information.165 """166167 #: if this environment is sandboxed. Modifying this variable won't make168 #: the environment sandboxed though. For a real sandboxed environment
594 unmodified lines
modified:jinja2/loaders.py+16 added-6 removed
84 unmodified lines
85 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 = {}9293 # 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)9693 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.code103104 # 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)108109 # 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)115116 return environment.template_class.from_code(environment, code,117 globals, uptodate)118
181 unmodified lines
modified:CHANGES+2 added
28 unmodified lines
29- added `sort` filter that works like `dictsort` but for arbitrary sequences.3031- fixed a bug with empty statements in macros.3233- implemented a bytecode cache system. (:ref:`bytecode-cache`)3435Version 2.036-----------37(codename jinjavitus, released on July 17th 2008)38
32 unmodified lines