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
Provenance
- Commit
64b08a0- Tree
a6ffc23- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
05be95a
7 files changed+325 added−15 removed
modified:jinja2/testsuite/__init__.py+12 added
36 unmodified lines37 38 ### use only these methods for testing. If you need standard39 ### unittest method, wrap them!40 41+ def setup(self):42+ pass43+44+ def teardown(self):45+ pass46+47+ def setUp(self):48+ self.setup()49+50+ def tearDown(self):51+ self.teardown()52+53 def assert_equal(self, a, b):54 return self.assertEqual(a, b)55 56 def assert_raises(self, *args, **kwargs):39 unmodified linesmodified:jinja2/testsuite/loader.py+41 added
7 unmodified lines8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11 import os12+import gc13+import sys14 import time15 import tempfile16 import unittest17 81 unmodified lines99 assert split_template_path('./foo/bar') == ['foo', 'bar']100 self.assert_raises(TemplateNotFound, split_template_path, '../foo')101 102 103+class ModuleLoaderTestCase(JinjaTestCase):104+ archive = None105+106+ 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))112+113+ def teardown(self):114+ super(ModuleLoaderTestCase, self).teardown()115+ os.remove(self.archive)116+ self.archive = None117+118+ 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()122+123+ 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()126+127+ 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__131+132+ assert hasattr(self.mod_env.loader.module, key)133+ assert name in sys.modules134+135+ # unset all, ensure the module is gone from sys.modules136+ self.mod_env = tmpl = None137+ gc.collect()138+ assert name not in sys.modules139+140+141 def suite():142 suite = unittest.TestSuite()143 suite.addTest(unittest.makeSuite(LoaderTestCase))144+ suite.addTest(unittest.makeSuite(ModuleLoaderTestCase))145 return suitemodified:jinja2/__init__.py+3 added-2 removed
36 unmodified lines37 from jinja2.environment import Environment, Template38 39 # loaders40 from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \41- DictLoader, FunctionLoader, PrefixLoader, ChoiceLoader41+ DictLoader, FunctionLoader, PrefixLoader, ChoiceLoader, \42+ ModuleLoader43 44 # bytecode caches45 from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \46 MemcachedBytecodeCache17 unmodified lines64 '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 lines52 return f53 unoptimize_before_dead_code = bool(unoptimize_before_dead_code().func_closure)54 55 56-def generate(node, environment, name, filename, stream=None):56+def 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 lines365 366 367 class CodeGenerator(NodeVisitor):368 368- 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_init379 380 # aliases for imports381 self.import_aliases = {}382 372 unmodified lines755 self.writeline('from jinja2.runtime import ' + ', '.join(exported))756 if not unoptimize_before_dead_code:757 self.writeline('dummy = lambda *x: None')758 759+ # if we want a deferred initialization we cannot move the760+ # environment into a local name761+ envenv = not self.defer_init and ', environment=environment' or ''762+763 # 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 lines785 # add the load name786 self.writeline('name = %r' % self.name)787 788 # 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)790 791 # process the root792 frame = Frame()793 frame.inspect(node.body)26 unmodified lines820 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 linesmodified:jinja2/environment.py+111 added-7 removed
413 unmodified lines414 stream = TokenStream(stream, name, filename)415 return stream416 417 @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 on3 unmodified lines427 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.431+432+ `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.435+436+ .. 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 lines499 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)502 503+ 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.508+509+ `extensions` and `filter_func` are passed to :meth:`list_templates`.510+ Each template returned will be compiled to the target folder or511+ zipfile.512+513+ .. versionadded:: 2.4514+ """515+ from jinja2.loaders import ModuleLoader516+ if log_function is None:517+ log_function = lambda x: None518+519+ 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)527+528+ 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()551+552+ log_function('Finished compiling templates')553+554+ 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.558+559+ 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.565+566+ 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 x578+579 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 lines763 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 rv775+776+ @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.780+781+ .. versionadded:: 2.4782+ """783+ return cls._from_namespace(environment, module_dict, globals)784+785+ @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']793 794 # render function and module795 t.root_render_func = namespace['root']796 t._module = None797 798 # debug and loader helpers799 t._debug_info = namespace['debug_info']700- t._uptodate = uptodate800+ t._uptodate = None801 802+ # store the reference803+ namespace['environment'] = environment804+ namespace['__jinja_template__'] = t805+806 return t807 808 def render(self, *args, **kwargs):809 """This method accepts the same arguments as the `dict` constructor:241 unmodified linesmodified:jinja2/loaders.py+141 added
6 unmodified lines7 8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11+import os12+import sys13+import weakref14+from types import ModuleType15 from os import path16 try:17 from hashlib import sha118 except ImportError:43 unmodified lines62 source = f.read().decode('utf-8')63 return source, path, lambda: mtime == getmtime(path)64 """65 66+ #: 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 = True71+72 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 a10 unmodified lines86 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)94 95+ 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')100+101 @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 not73 unmodified lines178 return False179 return contents, filename, uptodate180 raise TemplateNotFound(template)181 182+ 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)195 196+197 class 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 lines238 239 source = self.provider.get_resource_string(self.manager, p)240 return source.decode(self.encoding), filename, uptodate241 242+ 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 results261 262+263 class 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 lines277 source = self.mapping[template]278 return source, None, lambda: source != self.mapping.get(template)279 raise TemplateNotFound(template)280 281+ def list_templates(self):282+ return sorted(self.mapping)283 284+285 class 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 lines343 # re-raise the exception with the correct fileame here.344 # (the one that includes the prefix)345 raise TemplateNotFound(template)346 347+ 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 result353 354+355 class 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 lines375 return loader.get_source(environment, template)376 except TemplateNotFound:377 pass378 raise TemplateNotFound(template)379+380+ def list_templates(self):381+ found = set()382+ for loader in self.loaders:383+ found.update(loader.list_templates())384+ return sorted(found)385+386+387+class _TemplateModule(ModuleType):388+389+ 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__)395+396+397+class ModuleLoader(BaseLoader):398+ """This loader loads templates from precompiled templates.399+400+ Example usage:401+402+ >>> loader = ChoiceLoader([403+ ... ModuleLoader('/path/to/compiled/templates'),404+ ... FileSystemLoader('/path/to/templates')405+ ... ])406+ """407+408+ has_source_access = False409+410+ def __init__(self, path):411+ package_name = '_jinja2_module_templates_%x' % id(self)412+413+ # 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__ = path421+422+ sys.modules[package_name] = weakref.proxy(mod,423+ lambda x: sys.modules.pop(package_name, None))424+425+ # 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_name430+431+ @staticmethod432+ def get_template_key(name):433+ return 'tmpl_' + sha1(name.encode('utf-8')).hexdigest()434+435+ @staticmethod436+ def get_module_filename(name):437+ return ModuleLoader.get_template_key(name) + '.py'438+439+ @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)450+451+ # 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)454+455+ return environment.template_class.from_module_dict(456+ environment, mod.__dict__, globals)modified:CHANGES+4 added
7 unmodified lines8 - 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.16 17 - the _speedups C extension now supports Python 3.18 19 Version 2.3.1144 unmodified lines