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
Provenance
- Commit
4d5bdff- Tree
1a21ab9- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
205bae5
4 files changed+185 added−6 removed
added:jinja2/bccache.py+156 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja2.bccache4+ ~~~~~~~~~~~~~~5+6+ 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.10+11+ Situations where this is useful are often forking web applications that12+ are initialized on the first request.13+14+ :copyright: Copyright 2008 by Armin Ronacher.15+ :license: BSD.16+"""17+from os import path18+import marshal19+import cPickle as pickle20+from cStringIO import StringIO21+try:22+ from hashlib import sha123+except ImportError:24+ from sha import new as sha125+26+27+bc_version = 128+bc_magic = 'j2' + pickle.dumps(bc_version, 2)29+30+31+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.35+36+ The bucket then provides method to load the bytecode from file(-like)37+ objects and strings or dump it again.38+ """39+40+ def __init__(self, cache, environment, key, checksum):41+ self._cache = cache42+ self.environment = environment43+ self.key = key44+ self.checksum = checksum45+ self.reset()46+47+ def reset(self):48+ """Resets the bucket (unloads the code)."""49+ self.code = None50+51+ 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())69+70+ 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))80+81+ def loads(self, string):82+ """Load bytecode from a string."""83+ self.load(StringIO(string))84+85+ def dumps(self):86+ """Return the bytecode as string."""87+ out = StringIO()88+ self.dump(out)89+ return out.getvalue()90+91+ def write_back(self):92+ """Write the bucket back to the cache."""93+ self._cache.dump_bucket(self)94+95+96+class 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+ """101+102+ def load_bucket(self, bucket):103+ """Subclasses have to override this method to load bytecode104+ into a bucket.105+ """106+ raise NotImplementedError()107+108+ 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()113+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()117+118+ def get_source_checksum(self, source):119+ """Return a checksum for the source."""120+ return sha1(source.encode('utf-8')).hexdigest()121+122+ 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 bucket129+130+131+class FileSystemCache(BytecodeCache):132+ """A bytecode cache that stores bytecode on the filesystem."""133+134+ def __init__(self, directory, pattern='%s.jbc'):135+ self.directory = directory136+ self.pattern = pattern137+138+ def _get_cache_filename(self, bucket):139+ return path.join(self.directory, self.pattern % bucket.key)140+141+ 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()149+150+ 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 lines154 `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.158+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.163 """164 165 #: if this environment is sandboxed. Modifying this variable won't make166 #: the environment sandboxed though. For a real sandboxed environment26 unmodified lines193 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 least27 unmodified lines230 self.globals = DEFAULT_NAMESPACE.copy()231 232 # 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_reload238 239 # load extensions240 self.extensions = load_extensions(self, extensions)14 unmodified lines255 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 it240 unmodified lines505 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)511 512 @classmethod513 def from_code(cls, environment, code, globals, uptodate=None):247 unmodified linesmodified:jinja2/ext.py+3 added-2 removed
433 unmodified lines434 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 )442 443 source = fileobj.read().decode(options.get('encoding', 'utf-8'))444 try:12 unmodified linesmodified:jinja2/loaders.py+14 added-1 removed
87 unmodified lines88 """89 if globals is None:90 globals = {}91 source, filename, uptodate = self.get_source(environment, name)92+93+ code = bucket = None94+ if environment.bytecode_cache is not None:95+ bucket = environment.bytecode_cache.get_bucket(environment, name,96+ source)97+ code = bucket.code98+99+ if code is None:92- code = environment.compile(source, name, filename)100+ code = environment.compile(source, name, filename)101+102+ if bucket and bucket.code is None:103+ bucket.code = code104+ bucket.write_back()105+106 return environment.template_class.from_code(environment, code,107 globals, uptodate)108 109 180 unmodified lines