Skip to content
Myr

Added experimental and undocumented bytecode cache support

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 205bae5 · Browse files · 4 files+185 added−6 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+185 added−6 removed

  • other:+185 added−6 removed

4 files+185 added−6 removed

added:jinja2/bccache.py+156 added
1# -*- coding: utf-8 -*-2"""3 jinja2.bccache4 ~~~~~~~~~~~~~~56 This module implements the bytecode cache system Jinja is optionally7 using. This is useful if you have very complex template situations and8 the compiliation of all those templates slow down your application too9 much.1011 Situations where this is useful are often forking web applications that12 are initialized on the first request.1314 :copyright: Copyright 2008 by Armin Ronacher.15 :license: BSD.16"""17from os import path18import marshal19import cPickle as pickle20from cStringIO import StringIO21try:22 from hashlib import sha123except ImportError:24 from sha import new as sha1252627bc_version = 128bc_magic = 'j2' + pickle.dumps(bc_version, 2)293031class 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.3536 The bucket then provides method to load the bytecode from file(-like)37 objects and strings or dump it again.38 """3940 def __init__(self, cache, environment, key, checksum):41 self._cache = cache42 self.environment = environment43 self.key = key44 self.checksum = checksum45 self.reset()4647 def reset(self):48 """Resets the bucket (unloads the code)."""49 self.code = None5051 def load(self, f):52 """Loads bytecode from a f."""53 # make sure the magic header is correct54 magic = f.read(len(bc_magic))55 if magic != bc_magic:56 self.reset()57 return58 # the source code of the file changed, we need to reload59 checksum = pickle.load(f)60 if self.checksum != checksum:61 self.reset()62 return63 # now load the code. Because marshal is not able to load64 # from arbitrary streams we have to work around that65 if isinstance(f, file):66 self.code = marshal.load(f)67 else:68 self.code = marshal.loads(f.read())6970 def dump(self, f):71 """Dump the bytecode into f."""72 if self.code is None:73 raise TypeError('can\'t write empty bucket')74 f.write(bc_magic)75 pickle.dump(self.checksum, f, 2)76 if isinstance(f, file):77 marshal.dump(self.code, f)78 else:79 f.write(marshal.dumps(self.code))8081 def loads(self, string):82 """Load bytecode from a string."""83 self.load(StringIO(string))8485 def dumps(self):86 """Return the bytecode as string."""87 out = StringIO()88 self.dump(out)89 return out.getvalue()9091 def write_back(self):92 """Write the bucket back to the cache."""93 self._cache.dump_bucket(self)949596class BytecodeCache(object):97 """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.100 """101102 def load_bucket(self, bucket):103 """Subclasses have to override this method to load bytecode104 into a bucket.105 """106 raise NotImplementedError()107108 def dump_bucket(self, bucket):109 """Subclasses have to override this method to write the110 bytecode from a bucket back to the cache.111 """112 raise NotImplementedError()113114 def get_cache_key(self, name):115 """Return the unique hash key for this template name."""116 return sha1(name.encode('utf-8')).hexdigest()117118 def get_source_checksum(self, source):119 """Return a checksum for the source."""120 return sha1(source.encode('utf-8')).hexdigest()121122 def get_bucket(self, environment, name, source):123 """Return a cache bucket."""124 key = self.get_cache_key(name)125 checksum = self.get_source_checksum(source)126 bucket = Bucket(self, environment, key, checksum)127 self.load_bucket(bucket)128 return bucket129130131class FileSystemCache(BytecodeCache):132 """A bytecode cache that stores bytecode on the filesystem."""133134 def __init__(self, directory, pattern='%s.jbc'):135 self.directory = directory136 self.pattern = pattern137138 def _get_cache_filename(self, bucket):139 return path.join(self.directory, self.pattern % bucket.key)140141 def load_bucket(self, bucket):142 filename = self._get_cache_filename(bucket)143 if path.exists(filename):144 f = file(filename, 'rb')145 try:146 bucket.load(f)147 finally:148 f.close()149150 def dump_bucket(self, bucket):151 filename = self._get_cache_filename(bucket)152 f = file(filename, 'wb')153 try:154 bucket.dump(f)155 finally:156 f.close()
modified:jinja2/environment.py+12 added-3 removed
153 unmodified lines
154 `auto_reload` is set to `True` (default) every time a template is155 requested the loader checks if the source changed and if yes, it156 will reload the template. For higher performance it's possible to157 disable that.158159 `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 """164165 #: if this environment is sandboxed. Modifying this variable won't make166 #: the environment sandboxed though. For a real sandboxed environment
26 unmodified lines
193 finalize=None,194 autoescape=False,195 loader=None,196 cache_size=50,192 auto_reload=True):197 auto_reload=True,198 bytecode_cache=None):199 # !!Important notice!!200 # The constructor accepts quite a few arguments that should be201 # passed by keyword rather than position. However it's important to202 # not change the order of arguments because it's used at least
27 unmodified lines
230 self.globals = DEFAULT_NAMESPACE.copy()231232 # set the loader provided233 self.loader = loader234 self.bytecode_cache = None235 self.cache = create_cache(cache_size)236 self.bytecode_cache = bytecode_cache237 self.auto_reload = auto_reload238239 # load extensions240 self.extensions = load_extensions(self, extensions)
14 unmodified lines
255 comment_start_string=missing, comment_end_string=missing,256 line_statement_prefix=missing, trim_blocks=missing,257 extensions=missing, optimized=missing, undefined=missing,258 finalize=missing, autoescape=missing, loader=missing,251 cache_size=missing, auto_reload=missing):259 cache_size=missing, auto_reload=missing,260 bytecode_cache=missing):261 """Create a new overlay environment that shares all the data with the262 current environment except of cache and the overriden attributes.263 Extensions cannot be removed for a overlayed environment. A overlayed264 environment automatically gets all the extensions of the environment it
240 unmodified lines
505 block_start_string, block_end_string, variable_start_string,506 variable_end_string, comment_start_string, comment_end_string,507 line_statement_prefix, trim_blocks, newline_sequence,508 frozenset(extensions), optimized, undefined, finalize,500 autoescape, None, 0, False)509 autoescape, None, 0, False, None)510 return env.from_string(source, template_class=cls)511512 @classmethod513 def from_code(cls, environment, code, globals, uptodate=None):
247 unmodified lines
modified:jinja2/ext.py+3 added-2 removed
433 unmodified lines
434 NEWLINE_SEQUENCE, frozenset(extensions),435 # fill with defaults so that environments are shared436 # with other spontaneus environments. The rest of the437 # arguments are optimizer, undefined, finalize, autoescape,438 # loader, cache size and auto reloading setting439 True, Undefined, None, False, None, 0, False438 # loader, cache size, auto reloading setting and the439 # bytecode cache440 True, Undefined, None, False, None, 0, False, None441 )442443 source = fileobj.read().decode(options.get('encoding', 'utf-8'))444 try:
12 unmodified lines
modified:jinja2/loaders.py+14 added-1 removed
87 unmodified lines
88 """89 if globals is None:90 globals = {}91 source, filename, uptodate = self.get_source(environment, name)9293 code = bucket = None94 if environment.bytecode_cache is not None:95 bucket = environment.bytecode_cache.get_bucket(environment, name,96 source)97 code = bucket.code9899 if code is None:92 code = environment.compile(source, name, filename)100 code = environment.compile(source, name, filename)101102 if bucket and bucket.code is None:103 bucket.code = code104 bucket.write_back()105106 return environment.template_class.from_code(environment, code,107 globals, uptodate)108109
180 unmodified lines