[svn] implemented package loader
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 566295e · Browse files · 2 files·+231 added−110 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+231 added−110 removed
- other:+231 added−110 removed
Provenance
- Commit
be2456c- Tree
b72cb76- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
566295e
2 files changed+231 added−110 removed
modified:docs/src/loaders.txt+51 added-33 removed
11 unmodified lines12 Developing Loaders13 ==================14 15 Template loaders are just normal Python classes that have to provide some16-functions used to load and translate templates. Here is a simple loader implementation17-you can use as the base for your own loader:16+functions used to load and translate templates.17 18+Because some of the tasks a loader has to do are redundant there are mixin19+classes that make loader development easier.20+21+Here the implementation of a simple loader based on the `LoaderMixin` from22+`jinja.loaders`:23+24 .. sourcecode:: python25 26+ import codecs27 from os.path import join22- from jinja.parser import Parser28+ from jinja.loaders import LoaderMixin29 from jinja.exceptions import TemplateNotFound30 25- class SimpleLoader(object):26- """27- Slimmed down version of the included `FileSystemLoader`.28- """31+ class SimpleLoader(LoaderMixin):32+ 33+ def __init__(self, path):34+ self.path = path35 30- def __init__(self, searchpath):31- self.searchpath = searchpath32-36 def get_source(self, environment, name, parent):34- """35- The get_source function is unused at the moment. However, future36- versions of jinja will use this function for the debugging37- system. It also works as helper functions for `parse` and38- `load`.39- """40- filename = join(self.searchpath, name)37+ filename = join(self.path, name)38 if not path.exists(filename):39 raise TemplateNotFound(name)40 f = codecs.open(filename, 'r', environment.template_charset)41 try:42 return f.read()43 finally:44 f.close()45 49- def parse(self, environment, name, parent):50- """51- Load and parse a template and return the syntax tree.52- """53- source = self.get_source(environment, name, parent)54- return Parser(environment, source, name).parse()46+The functions `load` and `parse` which are a requirement for a loader are47+added automatically by the `LoaderMixin`.48 56- def load(self, environment, name, translator):57- """58- Parse and translate a template. Currently only translation to59- python code is possible, later Jinja versions however will60- support translating templates to javascript too.61- """62- return translator.process(environment, self.parse(environment, name, None))49+Additionally to the `LoaderMixin` there is a second mixin called50+`CachedLoaderMixin` that implements memory and disk caching of templates.51 52+It works basically the same, just that there are two more things to implement:53 65-.. admonition:: Note54+.. sourcecode:: python55 67- Once a loader is bound to an environment, you have to omit the environment68- argument for the public functions `get_source`, `parse` and `load`.56+ import codecs57+ from os.path import join, getmtime58+ from jinja.loaders import CachedLoaderMixin59+ from jinja.exceptions import TemplateNotFound60+61+ class CachedLoader(CachedLoaderMixin):62+ 63+ def __init__(self, path):64+ self.path = path65+ CachedLoaderMixin.__init__(66+ True, # use memory caching67+ 40, # for up to 40 templates68+ '/tmp', # additionally save the compiled templates in /tmp69+ True # and reload cached templates automaticall if changed70+ )71+72+ def get_source(self, environment, name, parent):73+ filename = join(self.path, name)74+ if not path.exists(filename):75+ raise TemplateNotFound(name)76+ f = codecs.open(filename, 'r', environment.template_charset)77+ try:78+ return f.read()79+ finally:80+ f.close()81+82+ def check_source_changed(self, environment, name):83+ return getmtime(join(self.path, name))84+85+You don't have to provide the `check_source_changed` method. If it doesn't86+exist the option `auto_reload` won't have an effect.modified:jinja/loaders.py+180 added-77 removed
16 unmodified lines17 from jinja.parser import Parser18 from jinja.translators.python import PythonTranslator, Template19 from jinja.exceptions import TemplateNotFound20 from jinja.utils import CacheDict21+try:22+ from pkg_resources import resource_exists, resource_string, \23+ resource_filename24+except ImportError:25+ resource_exists = resource_string = resource_filename = None26 27 23-__all__ = ['FileSystemLoader']28+__all__ = ['FileSystemLoader', 'PackageLoader']29 30 31 def get_template_filename(searchpath, name):32 """2 unmodified lines35 return path.join(searchpath, path.sep.join([p for p in name.split('/')36 if p and p[0] != '.']))37 38 34-def get_template_cachename(cachepath, name):39+def get_cachename(cachepath, name):40 """41 Return the filename for a cached file.42 """43 return path.join(cachepath, 'jinja_%s.cache' %44 unmodified lines88 def __nonzero__(self):89 return self.loader is not None90 91 87-class FileSystemLoader(object):92+class LoaderMixin(object):93 """94+ Use this class to implement loaders.95+96+ Just mixin this class and implement a method called `get_source`97+ with the signature (`environment`, `name`, `parent`) that returns98+ sourcecode for the template.99+100+ For more complex loaders you probably want to override `load` to101+ or not use the `LoaderMixin` at all.102+ """103+104+ def parse(self, environment, name, parent):105+ """106+ Load and parse a template107+ """108+ source = self.get_source(environment, name, parent)109+ return Parser(environment, source, name).parse()110+111+ def load(self, environment, name, translator):112+ """113+ Load and translate a template114+ """115+ ast = self.parse(environment, name, None)116+ return translator.process(environment, ast)117+118+119+class CachedLoaderMixin(LoaderMixin):120+ """121+ Works like the loader mixin just that it supports caching.122+ """123+124+ def __init__(self, use_memcache, cache_size, cache_folder, auto_reload):125+ if use_memcache:126+ self.__memcache = CacheDict(cache_size)127+ else:128+ self.__memcache = None129+ self.__cache_folder = cache_folder130+ if not hasattr(self, 'check_source_changed'):131+ self.__auto_reload = False132+ else:133+ self.__auto_reload = auto_reload134+ self.__times = {}135+ self.__lock = Lock()136+137+ def load(self, environment, name, translator):138+ self.__lock.acquire()139+ try:140+ # caching is only possible for the python translator. skip141+ # all other translators142+ if translator is PythonTranslator:143+ tmpl = None144+145+ # auto reload enabled? check for the last change of146+ # the template147+ if self.__auto_reload:148+ last_change = self.check_source_changed(environment, name)149+ else:150+ last_change = None151+152+ # check if we have something in the memory cache and the153+ # memory cache is enabled.154+ if self.__memcache is not None and name in self.__memcache:155+ tmpl = self.__memcache[name]156+ if last_change is not None and \157+ last_change > self.__times[name]:158+ tmpl = None159+160+ # if diskcache is enabled look for an already compiled161+ # template.162+ if self.__cache_folder is not None:163+ cache_fn = get_cachename(self.__cache_folder, name)164+165+ # there is an up to date compiled template166+ if tmpl is not None and last_change is None:167+ try:168+ cache_time = path.getmtime(cache_fn)169+ except OSError:170+ cache_time = 0171+ if last_change >= cache_time:172+ f = file(cache_fn, 'rb')173+ try:174+ tmpl = Template.load(environment, f)175+ finally:176+ f.close()177+178+ # no template so far, parse, translate and compile it179+ elif tmpl is None:180+ tmpl = LoaderMixin.load(self, environment,181+ name, translator)182+183+ # save the compiled template184+ f = file(cache_fn, 'wb')185+ try:186+ tmpl.dump(f)187+ finally:188+ f.close()189+190+ # if memcaching is enabled push the template191+ if tmpl is not None:192+ if self.__memcache is not None:193+ self.__times[name] = time.time()194+ self.__memcache[name] = tmpl195+ return tmpl196+197+ # if we reach this point we don't have caching enabled or translate198+ # to something else than python199+ return LoaderMixin.load(self, environment, name, translator)200+ finally:201+ self.__lock.release()202+203+204+class FileSystemLoader(CachedLoaderMixin):205+ """206 Loads templates from the filesystem:207 208 .. sourcecode:: python209 27 unmodified lines237 238 def __init__(self, searchpath, use_memcache=False, memcache_size=40,239 cache_folder=None, auto_reload=True):240 self.searchpath = searchpath124- self.use_memcache = use_memcache125- if use_memcache:126- self.memcache = CacheDict(memcache_size)127- else:128- self.memcache = None129- self.cache_folder = cache_folder130- self.auto_reload = auto_reload131- self._times = {}132- self._lock = Lock()241+ CachedLoaderMixin.__init__(self, use_memcache, memcache_size,242+ cache_folder, auto_reload)243 244 def get_source(self, environment, name, parent):135- """136- Get the source code of a template.137- """245 filename = get_template_filename(self.searchpath, name)246 if path.exists(filename):247 f = codecs.open(filename, 'r', environment.template_charset)248 try:2 unmodified lines251 f.close()252 else:253 raise TemplateNotFound(name)254 148- def parse(self, environment, name, parent):149- """150- Load and parse a template151- """152- source = self.get_source(environment, name, parent)153- return Parser(environment, source, name).parse()255+ def check_source_changed(self, environment, name):256+ return path.getmtime(get_template_filename(self.searchpath, name))257 155- def load(self, environment, name, translator):156- """157- Load, parse and translate a template.158- """159- self._lock.acquire()160- try:161- # caching is only possible for the python translator. skip162- # all other translators163- if translator is PythonTranslator:164- tmpl = None258 166- # auto reload enabled? check for the last change of the template167- if self.auto_reload:168- last_change = path.getmtime(get_template_filename(self.searchpath, name))169- else:170- last_change = None259+class PackageLoader(CachedLoaderMixin):260+ """261+ Loads templates from python packages using setuptools.262 172- # check if we have something in the memory cache and the173- # memory cache is enabled.174- if self.use_memcache and name in self.memcache:175- tmpl = self.memcache[name]176- if last_change is not None and last_change > self._times[name]:177- tmpl = None263+ .. sourcecode:: python264 179- # if diskcache is enabled look for an already compiled template180- if self.cache_folder is not None:181- cache_filename = get_template_cachename(self.cache_folder, name)265+ from jinja import Environment, PackageLoader266+ e = Environment(loader=PackageLoader('yourapp', 'template/path'))267 183- # there is a up to date compiled template184- if tmpl is not None and last_change is None:185- try:186- cache_time = path.getmtime(cache_filename)187- except OSError:188- cache_time = 0189- if last_change >= cache_time:190- f = file(cache_filename, 'rb')191- try:192- tmpl = Template.load(environment, f)193- finally:194- f.close()268+ You can pass the following keyword arguments to the loader on269+ initialisation:270 196- # no template so far, parse, translate and compile it197- elif tmpl is None:198- tmpl = translator.process(environment, self.parse(environment, name, None))271+ =================== =================================================272+ ``package_name`` Name of the package containing the templates.273+ ``package_path`` Path of the templates inside the package.274+ ``use_memcache`` Set this to ``True`` to enable memory caching.275+ This is usually a good idea in production mode,276+ but disable it during development since it won't277+ reload template changes automatically.278+ This only works in persistent environments like279+ FastCGI.280+ ``memcache_size`` Number of template instance you want to cache.281+ Defaults to ``40``.282+ ``cache_folder`` Set this to an existing directory to enable283+ caching of templates on the file system. Note284+ that this only affects templates transformed285+ into python code. Default is ``None`` which means286+ that caching is disabled.287+ ``auto_reload`` Set this to `False` for a slightly better288+ performance. In that case Jinja won't check for289+ template changes on the filesystem. If the290+ templates are inside of an egg file this won't291+ have an effect.292+ =================== =================================================293+ """294 200- # save the compiled template201- f = file(cache_filename, 'wb')202- try:203- tmpl.dump(f)204- finally:205- f.close()295+ def __init__(self, package_name, package_path, use_memcache=False,296+ memcache_size=40, cache_folder=None, auto_reload=True):297+ if resource_filename is None:298+ raise ImportError('setuptools not found')299+ self.package_name = package_name300+ self.package_path = package_path301+ # if we have an loader we probably retrieved it from an egg302+ # file. In that case don't use the auto_reload!303+ if auto_reload:304+ package = __import__(package_name, '', '', [''])305+ if package.__loader__ is not None:306+ auto_reload = False307+ CachedLoaderMixin.__init__(self, use_memcache, memcache_size,308+ cache_folder, auto_reload)309 207- # if memcaching is enabled push the template208- if tmpl is not None:209- if self.use_memcache:210- self._times[name] = time.time()211- self.memcache[name] = tmpl212- return tmpl310+ def get_source(self, environment, name, parent):311+ name = '/'.join([self.package_path] + [p for p in name.split('/')312+ if p and p[0] != '.'])313+ if not resource_exists(self.package, name):314+ raise TemplateNotFound(name)315+ contents = resource_string(self.package_name, name)316+ return contents.decode(environment.template_charset)317 214- # if we reach this point we don't have caching enabled or translate215- # to something else than python216- return translator.process(environment, self.parse(environment, name, None))217- finally:218- self._lock.release()318+ def check_source_changed(self, environment, name):319+ name = '/'.join([self.package_path] + [p for p in name.split('/')320+ if p and p[0] != '.'])321+ return path.getmtime(resource_filename(name))