Skip to content
Myr

added a :class:`ModuleLoader` that can load templates from

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

precompiled sources. The environment now features a method to compile the templates from a configured loader into a zip file or folder. --HG-- branch : trunk extra : rebase_source : 4824f663e4ff58ca3d2176c65fc1b7494e1f0c43

authored by Armin Ronacher · committed by Armin Ronacher · parent 05be95a · Browse files · 7 files+325 added−15 removed
This commit

State

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

Diff stats

7 files+325 added−15 removed

  • other:+325 added−15 removed

7 files+325 added−15 removed

modified:jinja2/testsuite/__init__.py+12 added
36 unmodified lines
3738 ### use only these methods for testing. If you need standard39 ### unittest method, wrap them!4041 def setup(self):42 pass4344 def teardown(self):45 pass4647 def setUp(self):48 self.setup()4950 def tearDown(self):51 self.teardown()5253 def assert_equal(self, a, b):54 return self.assertEqual(a, b)5556 def assert_raises(self, *args, **kwargs):
39 unmodified lines
modified:jinja2/testsuite/loader.py+41 added
7 unmodified lines
8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11import os12import gc13import sys14import time15import tempfile16import unittest17
81 unmodified lines
99 assert split_template_path('./foo/bar') == ['foo', 'bar']100 self.assert_raises(TemplateNotFound, split_template_path, '../foo')101102103class ModuleLoaderTestCase(JinjaTestCase):104 archive = None105106 def setup(self):107 super(ModuleLoaderTestCase, self).setup()108 self.reg_env = Environment(loader=prefix_loader)109 self.archive = tempfile.mkstemp(suffix='.zip')[1]110 self.reg_env.compile_templates(self.archive)111 self.mod_env = Environment(loader=loaders.ModuleLoader(self.archive))112113 def teardown(self):114 super(ModuleLoaderTestCase, self).teardown()115 os.remove(self.archive)116 self.archive = None117118 def test_module_loader(self):119 tmpl1 = self.reg_env.get_template('a/test.html')120 tmpl2 = self.mod_env.get_template('a/test.html')121 assert tmpl1.render() == tmpl2.render()122123 tmpl1 = self.reg_env.get_template('b/justdict.html')124 tmpl2 = self.mod_env.get_template('b/justdict.html')125 assert tmpl1.render() == tmpl2.render()126127 def test_weak_references(self):128 tmpl = self.mod_env.get_template('a/test.html')129 key = loaders.ModuleLoader.get_template_key('a/test.html')130 name = self.mod_env.loader.module.__name__131132 assert hasattr(self.mod_env.loader.module, key)133 assert name in sys.modules134135 # unset all, ensure the module is gone from sys.modules136 self.mod_env = tmpl = None137 gc.collect()138 assert name not in sys.modules139140141def suite():142 suite = unittest.TestSuite()143 suite.addTest(unittest.makeSuite(LoaderTestCase))144 suite.addTest(unittest.makeSuite(ModuleLoaderTestCase))145 return suite
modified:jinja2/__init__.py+3 added-2 removed
36 unmodified lines
37from jinja2.environment import Environment, Template3839# loaders40from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \41 DictLoader, FunctionLoader, PrefixLoader, ChoiceLoader41 DictLoader, FunctionLoader, PrefixLoader, ChoiceLoader, \42 ModuleLoader4344# bytecode caches45from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \46 MemcachedBytecodeCache
17 unmodified lines
64 'ChoiceLoader', 'BytecodeCache', 'FileSystemBytecodeCache',65 'MemcachedBytecodeCache', 'Undefined', 'DebugUndefined',66 'StrictUndefined', 'TemplateError', 'UndefinedError', 'TemplateNotFound',67 'TemplatesNotFound', 'TemplateSyntaxError', 'TemplateAssertionError',67 'environmentfilter', 'contextfilter', 'Markup', 'escape',68 'ModuleLoader', 'environmentfilter', 'contextfilter', 'Markup', 'escape',69 'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined'70]
modified:jinja2/compiler.py+13 added-6 removed
51 unmodified lines
52 return f53unoptimize_before_dead_code = bool(unoptimize_before_dead_code().func_closure)545556def generate(node, environment, name, filename, stream=None):56def generate(node, environment, name, filename, stream=None,57 defer_init=False):58 """Generate the python source for a node tree."""59 if not isinstance(node, nodes.Template):60 raise TypeError('Can\'t compile non template nodes')60 generator = CodeGenerator(environment, name, filename, stream)61 generator = CodeGenerator(environment, name, filename, stream, defer_init)62 generator.visit(node)63 if stream is None:64 return generator.stream.getvalue()65
299 unmodified lines
365366367class CodeGenerator(NodeVisitor):368368 def __init__(self, environment, name, filename, stream=None):369 def __init__(self, environment, name, filename, stream=None,370 defer_init=False):371 if stream is None:372 stream = StringIO()373 self.environment = environment374 self.name = name375 self.filename = filename376 self.stream = stream377 self.created_block_context = False378 self.defer_init = defer_init379380 # aliases for imports381 self.import_aliases = {}382
372 unmodified lines
755 self.writeline('from jinja2.runtime import ' + ', '.join(exported))756 if not unoptimize_before_dead_code:757 self.writeline('dummy = lambda *x: None')758759 # if we want a deferred initialization we cannot move the760 # environment into a local name761 envenv = not self.defer_init and ', environment=environment' or ''762763 # do we have an extends tag at all? If not, we can save some764 # overhead by just not processing any inheritance code.765 have_extends = node.find(nodes.Extends) is not None766
18 unmodified lines
785 # add the load name786 self.writeline('name = %r' % self.name)787788 # generate the root render function.782 self.writeline('def root(context, environment=environment):', extra=1)789 self.writeline('def root(context%s):' % envenv, extra=1)790791 # process the root792 frame = Frame()793 frame.inspect(node.body)
26 unmodified lines
820 for name, block in self.blocks.iteritems():821 block_frame = Frame()822 block_frame.inspect(block.body)823 block_frame.block = name817 self.writeline('def block_%s(context, environment=environment):'818 % name, block, 1)824 self.writeline('def block_%s(context%s):' % (name, envenv),825 block, 1)826 self.indent()827 undeclared = find_undeclared(block.body, ('self', 'super'))828 if 'self' in undeclared:829 block_frame.identifiers.add_special('self')
748 unmodified lines
modified:jinja2/environment.py+111 added-7 removed
413 unmodified lines
414 stream = TokenStream(stream, name, filename)415 return stream416417 @internalcode418 def compile(self, source, name=None, filename=None, raw=False):418 def compile(self, source, name=None, filename=None, raw=False,419 defer_init=False):420 """Compile a node or template source code. The `name` parameter is421 the load name of the template after it was joined using422 :meth:`join_path` if necessary, not the filename on the file system.423 the `filename` parameter is the estimated filename of the template on
3 unmodified lines
427 The return value of this method is a python code object. If the `raw`428 parameter is `True` the return value will be a string with python429 code equivalent to the bytecode returned otherwise. This method is430 mainly used internally.431432 `defer_init` is use internally to aid the module code generator. This433 causes the generated code to be able to import without the global434 environment variable to be set.435436 .. versionadded:: 2.4437 `defer_init` parameter added.438 """439 source_hint = None440 try:441 if isinstance(source, basestring):442 source_hint = source443 source = self._parse(source, name, filename)444 if self.optimized:445 source = optimize(source, self)438 source = generate(source, self, name, filename)446 source = generate(source, self, name, filename,447 defer_init=defer_init)448 if raw:449 return source450 if filename is None:451 filename = '<template>'
47 unmodified lines
499 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]500 template = self.from_string(nodes.Template(body, lineno=1))501 return TemplateExpression(template, undefined_to_none)502503 def compile_templates(self, target, extensions=None, filter_func=None,504 zip=True, log_function=None):505 """Compiles all the templates the loader can find, compiles them506 and stores them in `target`. If `zip` is true, a zipfile will be507 written, otherwise the templates are stored in a directory.508509 `extensions` and `filter_func` are passed to :meth:`list_templates`.510 Each template returned will be compiled to the target folder or511 zipfile.512513 .. versionadded:: 2.4514 """515 from jinja2.loaders import ModuleLoader516 if log_function is None:517 log_function = lambda x: None518519 if zip:520 from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED521 f = ZipFile(target, 'w', ZIP_DEFLATED)522 log_function('Compiling into Zip archive "%s"' % target)523 else:524 if not os.path.isdir(target):525 os.makedirs(target)526 log_function('Compiling into folder "%s"' % target)527528 try:529 for name in self.list_templates(extensions, filter_func):530 source, filename, _ = self.loader.get_source(self, name)531 try:532 code = self.compile(source, name, filename, True, True)533 except TemplateSyntaxError, e:534 log_function('Could not compile "%s": %s' % (name, e))535 continue536 module = ModuleLoader.get_module_filename(name)537 if zip:538 info = ZipInfo(module)539 info.external_attr = 0755 << 16L540 f.writestr(info, code)541 else:542 f = open(filename, 'w')543 try:544 f.write(code)545 finally:546 f.close()547 log_function('Compiled "%s" as %s' % (name, module))548 finally:549 if zip:550 f.close()551552 log_function('Finished compiling templates')553554 def list_templates(self, extensions=None, filter_func=None):555 """Returns a list of templates for this environment. This requires556 that the loader supports the loader's557 :meth:`~BaseLoader.list_templates` method.558559 If there are other files in the template folder besides the560 actual templates, the returned list can be filtered. There are two561 ways: either `extensions` is set to a list of file extensions for562 templates, or a `filter_func` can be provided which is a callable that563 is passed a template name and should return `True` if it should end up564 in the result list.565566 If the loader does not support that, a :exc:`TypeError` is raised.567 """568 x = self.loader.list_templates()569 if extensions is not None:570 if filter_func is not None:571 raise TypeError('either extensions or filter_func '572 'can be passed, but not both')573 filter_func = lambda x: '.' in x and \574 x.rsplit('.', 1)[1] in extensions575 if filter_func is not None:576 x = filter(filter_func, x)577 return x578579 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):580 """Exception handling helper. This is used internally to either raise581 rewritten exceptions or return a rendered traceback for the template.582 """
180 unmodified lines
763 def from_code(cls, environment, code, globals, uptodate=None):764 """Creates a template object from compiled code and the globals. This765 is used by the loaders and environment to create a template object.766 """682 t = object.__new__(cls)767 namespace = {684 'environment': environment,685 '__jinja_template__': t768 'environment': environment,769 '__file__': code.co_filename770 }771 exec code in namespace772 rv = cls._from_namespace(environment, namespace, globals)773 rv._uptodate = uptodate774 return rv775776 @classmethod777 def from_module_dict(cls, environment, module_dict, globals):778 """Creates a template object from a module. This is used by the779 module loader to create a template object.780781 .. versionadded:: 2.4782 """783 return cls._from_namespace(environment, module_dict, globals)784785 @classmethod786 def _from_namespace(cls, environment, namespace, globals):787 t = object.__new__(cls)788 t.environment = environment789 t.globals = globals790 t.name = namespace['name']691 t.filename = code.co_filename791 t.filename = namespace['__file__']792 t.blocks = namespace['blocks']793794 # render function and module795 t.root_render_func = namespace['root']796 t._module = None797798 # debug and loader helpers799 t._debug_info = namespace['debug_info']700 t._uptodate = uptodate800 t._uptodate = None801802 # store the reference803 namespace['environment'] = environment804 namespace['__jinja_template__'] = t805806 return t807808 def render(self, *args, **kwargs):809 """This method accepts the same arguments as the `dict` constructor:
241 unmodified lines
modified:jinja2/loaders.py+141 added
6 unmodified lines
78 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11import os12import sys13import weakref14from types import ModuleType15from os import path16try:17 from hashlib import sha118except ImportError:
43 unmodified lines
62 source = f.read().decode('utf-8')63 return source, path, lambda: mtime == getmtime(path)64 """6566 #: if set to `False` it indicates that the loader cannot provide access67 #: to the source of templates.68 #:69 #: .. versionadded:: 2.470 has_source_access = True7172 def get_source(self, environment, template):73 """Get the template source, filename and reload helper for a template.74 It's passed the environment and template name and has to return a75 tuple in the form ``(source, filename, uptodate)`` or raise a
10 unmodified lines
86 changed. No arguments are passed so the function must store the87 old state somewhere (for example in a closure). If it returns `False`88 the template will be reloaded.89 """90 if not self.has_source_access:91 raise RuntimeError('%s cannot provide access to the source' %92 self.__class__.__name__)93 raise TemplateNotFound(template)9495 def list_templates(self):96 """Iterates over all templates. If the loader does not support that97 it should raise a :exc:`TypeError` which is the default behavior.98 """99 raise TypeError('this loader cannot iterate over all templates')100101 @internalcode102 def load(self, environment, name, globals=None):103 """Loads a template. This method looks up the template in the cache104 or loads one by calling :meth:`get_source`. Subclasses should not
73 unmodified lines
178 return False179 return contents, filename, uptodate180 raise TemplateNotFound(template)181182 def list_templates(self):183 found = set()184 for searchpath in self.searchpath:185 for dirpath, dirnames, filenames in os.walk(searchpath):186 for filename in filenames:187 template = os.path.join(dirpath, filename) \188 [len(searchpath):].strip(os.path.sep) \189 .replace(os.path.sep, '/')190 if template[:2] == './':191 template = template[2:]192 if template not in found:193 found.add(template)194 return sorted(found)195196197class PackageLoader(BaseLoader):198 """Load templates from python eggs or packages. It is constructed with199 the name of the python package and the path to the templates in that200 package::
37 unmodified lines
238239 source = self.provider.get_resource_string(self.manager, p)240 return source.decode(self.encoding), filename, uptodate241242 def list_templates(self):243 path = self.package_path244 if path[:2] == './':245 path = path[2:]246 elif path == '.':247 path = ''248 offset = len(path)249 results = []250 def _walk(path):251 for filename in self.provider.resource_listdir(path):252 fullname = path + '/' + filename253 if self.provider.resource_isdir(fullname):254 for item in _walk(fullname):255 results.append(item)256 else:257 results.append(fullname[offset:].lstrip('/'))258 _walk(path)259 results.sort()260 return results261262263class DictLoader(BaseLoader):264 """Loads a template from a python dict. It's passed a dict of unicode265 strings bound to template names. This loader is useful for unittesting:266
10 unmodified lines
277 source = self.mapping[template]278 return source, None, lambda: source != self.mapping.get(template)279 raise TemplateNotFound(template)280281 def list_templates(self):282 return sorted(self.mapping)283284285class FunctionLoader(BaseLoader):286 """A loader that is passed a function which does the loading. The287 function becomes the name of the template passed and has to return either288 an unicode string with the template source, a tuple in the form ``(source,
54 unmodified lines
343 # re-raise the exception with the correct fileame here.344 # (the one that includes the prefix)345 raise TemplateNotFound(template)346347 def list_templates(self):348 result = []349 for prefix, loader in self.mapping.iteritems():350 for template in loader.list_templates():351 result.append(prefix + self.delimiter + template)352 return result353354355class ChoiceLoader(BaseLoader):356 """This loader works like the `PrefixLoader` just that no prefix is357 specified. If a template could not be found by one loader the next one358 is tried.
16 unmodified lines
375 return loader.get_source(environment, template)376 except TemplateNotFound:377 pass378 raise TemplateNotFound(template)379380 def list_templates(self):381 found = set()382 for loader in self.loaders:383 found.update(loader.list_templates())384 return sorted(found)385386387class _TemplateModule(ModuleType):388389 def __init__(self, module):390 if isinstance(module, basestring):391 super(_TemplateModule, self).__init__(module)392 else:393 super(_TemplateModule, self).__init__(module.__name__)394 self.__dict__.update(module.__dict__)395396397class ModuleLoader(BaseLoader):398 """This loader loads templates from precompiled templates.399400 Example usage:401402 >>> loader = ChoiceLoader([403 ... ModuleLoader('/path/to/compiled/templates'),404 ... FileSystemLoader('/path/to/templates')405 ... ])406 """407408 has_source_access = False409410 def __init__(self, path):411 package_name = '_jinja2_module_templates_%x' % id(self)412413 # create a fake module that looks for the templates in the414 # path given.415 mod = _TemplateModule(package_name)416 if isinstance(path, basestring):417 path = [path]418 else:419 path = list(path)420 mod.__path__ = path421422 sys.modules[package_name] = weakref.proxy(mod,423 lambda x: sys.modules.pop(package_name, None))424425 # the only strong reference, the sys.modules entry is weak426 # so that the garbage collector can remove it once the427 # loader that created it goes out of business.428 self.module = mod429 self.package_name = package_name430431 @staticmethod432 def get_template_key(name):433 return 'tmpl_' + sha1(name.encode('utf-8')).hexdigest()434435 @staticmethod436 def get_module_filename(name):437 return ModuleLoader.get_template_key(name) + '.py'438439 @internalcode440 def load(self, environment, name, globals=None):441 key = self.get_template_key(name)442 module = '%s.%s' % (self.package_name, key)443 mod = getattr(self.module, module, None)444 if mod is None:445 try:446 mod = _TemplateModule(__import__(module, None,447 None, ['root']))448 except ImportError:449 raise TemplateNotFound(name)450451 # remove the entry from sys.modules, we only want the attribute452 # on the module object we have stored on the loader.453 sys.modules.pop(module, None)454455 return environment.template_class.from_module_dict(456 environment, mod.__dict__, globals)
modified:CHANGES+4 added
7 unmodified lines
8- the environment template loading functions now transparently9 pass through a template object if it was passed to it. This10 makes it possible to import or extend from a template object11 that was passed to the template.12- added a :class:`ModuleLoader` that can load templates from13 precompiled sources. The environment now features a method14 to compile the templates from a configured loader into a zip15 file or folder.1617- the _speedups C extension now supports Python 3.1819Version 2.3.1
144 unmodified lines