Skip to content
Myr

[svn] added baseclasses for loaders, added the memcaching loader, updated documentation for loaders

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 ecc051b · Browse files · 7 files+332 added−52 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+332 added−52 removed

  • tests:+6 added−0 removed
  • other:+326 added−52 removed

7 files+332 added−52 removed

modified:docs/src/loaders.txt+54 added-2 removed
5 unmodified lines
67Builtin Loaders8===============910This list contains the builtin loaders you can use without further11modification:1213[[list_of_loaders]]1415Loader Baseclasses16==================1718With Jinja 1.1 onwards all the loaders have (except of the uncached) now have19baseclasses you can use to mix your own caching layer in. This technique is20explained below. The `BaseLoader` itself is also a loader baseclass but because21it's the baseclass of each loader it's explained in detail below.2223[[list_of_baseloaders]]2425Developing Loaders26==================2728Template loaders are just normal Python classes that have to provide some
26 unmodified lines
55 finally:56 f.close()5758The functions `load` and `parse` which are a requirement for a loader are46added automatically by the `BaseLoader`.59added automatically by the `BaseLoader`. Instead of the normal `BaseLoader`60you can use one of the other base loaders that already come with a proper61`get_source` method for further modification. Those loaders however are62new in Jinja 1.1.6364CachedLoaderMixin65-----------------6667Additionally to the `BaseLoader` there is a mixin class called68`CachedLoaderMixin` that implements memory and disk caching of templates.69Note that you have to give it a higher priority in the MRO than the70`BaseLoader` which means that's the first base class when inheriting from it:
38 unmodified lines
109You don't have to provide the `check_source_changed` method. If it doesn't110exist the option `auto_reload` won't have an effect. Also note that the111`check_source_changed` method must not raise an exception if the template112does not exist but return ``-1``. The return value ``-1`` is considered94"always reload" whereas ``0`` means "do not reload".113"always reload" whereas ``0`` means "do not reload". The default return114value for not existing templates should be ``-1``.115116For the default base classes that come with Jinja 1.1 onwards there exist117also concrete implementations that support caching. The implementation118just mixes in the `CachedLoaderMixin`.119120MemcachedLoaderMixin121--------------------122123*New in Jinja 1.1*124125The `MemcachedLoaderMixin` class adds support for `memcached`_ caching.126There is only one builtin loader that mixes it in: The127`MemcachedFileSystemLoader`. If you need other loaders with this mixin128you can easily subclass one of the existing base loaders. Here an example129for the `FunctionLoader`:130131.. sourcecode:: python132133 from jinja.loaders import FunctionLoader, MemcachedLoaderMixin134135 class MemcachedFunctionLoader(MemcachedLoaderMixin, FunctionLoader):136137 def __init__(self, loader_func):138 BaseFunctionLoader.__init__(self, loader_func)139 MemcachedLoaderMixin.__init__(self,140 True, # use memcached141 60 * 60 * 24 * 7, # 7 days expiration142 ['127.0.0.1:11211'], # the memcached hosts143 'template/' # string prefix for the cache keys144 )145146.. _memcached: http://www.danga.com/memcached/
modified:docs/generate.py+26 added
99 unmodified lines
100 result.append('`%s`\n%s' % (loader.__name__, '\n'.join(doclines)))101102 return '\n\n'.join(result)103104def generate_list_of_baseloaders():105 from jinja import loaders as loader_module106107 result = []108 loaders = []109 for item in dir(loader_module):110 obj = getattr(loader_module, item)111 try:112 if issubclass(obj, loader_module.BaseLoader) and \113 obj.__name__ != 'BaseLoader' and \114 obj.__name__ not in loader_module.__all__:115 loaders.append(obj)116 except TypeError:117 pass118 loaders.sort(key=lambda x: x.__name__.lower())119120 for loader in loaders:121 doclines = []122 for line in inspect.getdoc(loader).splitlines():123 doclines.append(' ' + line)124 result.append('`%s`\n%s' % (loader.__name__, '\n'.join(doclines)))125126 return '\n\n'.join(result)127128def generate_environment_doc():129 from jinja.environment import Environment130 return '%s\n\n%s' % (131 inspect.getdoc(Environment),
6 unmodified lines
138139LIST_OF_FILTERS = generate_list_of_filters()140LIST_OF_TESTS = generate_list_of_tests()141LIST_OF_LOADERS = generate_list_of_loaders()142LIST_OF_BASELOADERS = generate_list_of_baseloaders()143ENVIRONMENT_DOC = generate_environment_doc()144CHANGELOG = file(os.path.join(os.path.dirname(__file__), os.pardir, 'CHANGES'))\145 .read().decode('utf-8')146
117 unmodified lines
264 writer = DocumentationWriter(link_style)265 data = data.replace('[[list_of_filters]]', LIST_OF_FILTERS)\266 .replace('[[list_of_tests]]', LIST_OF_TESTS)\267 .replace('[[list_of_loaders]]', LIST_OF_LOADERS)\268 .replace('[[list_of_baseloaders]]', LIST_OF_BASELOADERS)\269 .replace('[[environment_doc]]', ENVIRONMENT_DOC)\270 .replace('[[changelog]]', CHANGELOG)271 parts = publish_parts(272 data,
53 unmodified lines
modified:jinja/loaders.py+237 added-49 removed
3 unmodified lines
4 ~~~~~~~~~~~~~56 Jinja loader classes.78 :copyright: 2007 by Armin Ronacher.8 :copyright: 2007 by Armin Ronacher, Bryan McLemore.9 :license: BSD, see LICENSE for more details.10"""1112import codecs
8 unmodified lines
212223#: when updating this, update the listing in the jinja package too24__all__ = ['FileSystemLoader', 'PackageLoader', 'DictLoader', 'ChoiceLoader',25 'FunctionLoader']25 'FunctionLoader', 'MemcachedFileSystemLoader']262728def get_template_filename(searchpath, name):29 """
111 unmodified lines
141142143class CachedLoaderMixin(object):144 """145 Mixin this class to implement simple memory and disk caching.145 Mixin this class to implement simple memory and disk caching. The146 memcaching just uses a dict in the loader so if you have a global147 environment or at least a global loader this can speed things up.148149 If the memcaching is enabled you can use (with Jinja 1.1 onwards)150 the `clear_memcache` function to clear the cache.151152 For memcached support check the `MemcachedLoaderMixin`.153 """154155 def __init__(self, use_memcache, cache_size, cache_folder, auto_reload,156 cache_salt=None):
9 unmodified lines
166 self.__salt = cache_salt167 self.__times = {}168 self.__lock = Lock()169170 def clear_memcache(self):171 """172 Clears the memcache.173 """174 if self.__memcache is not None:175 self.__memcache.clear()176177 def load(self, environment, name, translator):178 """179 Load and translate a template. First we check if there is a180 cached version of this template in the memory cache. If this is181 not the cache check for a compiled template in the disk cache168 folder. And if none of this is the case we translate the temlate169 using the `LoaderMixin.load` function, cache and return it.182 folder. And if none of this is the case we translate the temlate,183 cache and return it.184 """185 self.__lock.acquire()186 try:187 # caching is only possible for the python translator. skip
18 unmodified lines
206 if self.__memcache is not None:207 if name in self.__memcache:208 tmpl = self.__memcache[name]209 # if auto reload is enabled check if the template changed196 if last_change is not None and \197 last_change > self.__times[name]:210 if last_change and last_change > self.__times[name]:211 tmpl = None212 push_to_memory = True213 else:214 push_to_memory = True
44 unmodified lines
259 finally:260 self.__lock.release()261262250class FileSystemLoader(CachedLoaderMixin, BaseLoader):263class MemcachedLoaderMixin(object):264 """265 Uses a memcached server to cache the templates.266 """267268 def __init__(self, use_memcache, memcache_time=60 * 60 * 24 * 7,269 memcache_host=None, item_prefix='template/'):270 try:271 from memcache import Client272 except ImportError:273 raise RuntimeError('the %r loader requires an installed '274 'memcache module' % self.__class__.__name__)275 if memcache_host is None:276 memcache_host = ['127.0.0.1:11211']277 if use_memcache:278 self.__memcache = Client(list(memcache_host))279 self.__memcache_time = memcache_time280 else:281 self.__memcache = None282 self.__item_prefix = item_prefix283 self.__lock = Lock()284285 def load(self, environment, name, translator):286 """287 Load and translate a template. First we check if there is a288 cached version of this template in the memory cache. If this is289 not the cache check for a compiled template in the disk cache290 folder. And if none of this is the case we translate the template,291 cache and return it.292 """293 self.__lock.acquire()294 try:295 # caching is only possible for the python translator. skip296 # all other translators297 if translator is not PythonTranslator:298 return super(MemcachedLoaderMixin, self).load(299 environment, name, translator)300 tmpl = None301 push_to_memory = False302303 # check if we have something in the memory cache and the304 # memory cache is enabled.305 if self.__memcache is not None:306 bytecode = self.__memcache.get(self.__item_prefix + name)307 if bytecode:308 tmpl = Template.load(environment, bytecode)309 else:310 push_to_memory = True311312 # if we still have no template we load, parse and translate it.313 if tmpl is None:314 tmpl = super(MemcachedLoaderMixin, self).load(315 environment, name, translator)316317 # if memcaching is enabled and the template not loaded318 # we add that there.319 if push_to_memory:320 self.__memcache.set(self.__item_prefix + name, tmpl.dump(),321 self.__memcache_time)322 return tmpl323 finally:324 self.__lock.release()325326327class BaseFileSystemLoader(BaseLoader):328 """329 Baseclass for the file system loader that does not do any caching.330 It exists to avoid redundant code, just don't use it without subclassing.331332 How subclassing can work:333334 .. sourcecode:: python335336 from jinja.loaders import BaseFileSystemLoader337338 class MyFileSystemLoader(BaseFileSystemLoader):339 def __init__(self):340 BaseFileSystemLoader.__init__(self, '/path/to/templates')341342 The base file system loader only takes one parameter beside self which343 is the path to the templates.344 """345346 def __init__(self, searchpath):347 self.searchpath = path.abspath(searchpath)348349 def get_source(self, environment, name, parent):350 filename = get_template_filename(self.searchpath, name)351 if path.exists(filename):352 f = codecs.open(filename, 'r', environment.template_charset)353 try:354 return f.read()355 finally:356 f.close()357 else:358 raise TemplateNotFound(name)359360361class FileSystemLoader(CachedLoaderMixin, BaseFileSystemLoader):362 """363 Loads templates from the filesystem:364365 .. sourcecode:: python366367 from jinja import Environment, FileSystemLoader368 e = Environment(loader=FileSystemLoader('templates/'))369370 You can pass the following keyword arguments to the loader on260 initialisation:371 initialization:372373 =================== =================================================374 ``searchpath`` String with the path to the templates on the375 filesystem.
21 unmodified lines
397 """398399 def __init__(self, searchpath, use_memcache=False, memcache_size=40,400 cache_folder=None, auto_reload=True, cache_salt=None):290 self.searchpath = path.abspath(searchpath)401 BaseFileSystemLoader.__init__(self, searchpath)402403 if cache_salt is None:404 cache_salt = self.searchpath405 CachedLoaderMixin.__init__(self, use_memcache, memcache_size,406 cache_folder, auto_reload, cache_salt)407296 def get_source(self, environment, name, parent):297 filename = get_template_filename(self.searchpath, name)298 if path.exists(filename):299 f = codecs.open(filename, 'r', environment.template_charset)300 try:301 return f.read()302 finally:303 f.close()304 else:305 raise TemplateNotFound(name)306408 def check_source_changed(self, environment, name):409 filename = get_template_filename(self.searchpath, name)410 if path.exists(filename):411 return path.getmtime(filename)412 return -1413414314class PackageLoader(CachedLoaderMixin, BaseLoader):415class MemcachedFileSystemLoader(MemcachedLoaderMixin, BaseFileSystemLoader):416 """417 Loads templates from the filesystem and caches them on a memcached418 server.419420 .. sourcecode:: python421422 from jinja import Environment, MemcachedFileSystemLoader423 e = Environment(loader=MemcachedFileSystemLoader('templates/',424 memcache_host=['192.168.2.250:11211']425 ))426427 You can pass the following keyword arguments to the loader on428 initialization:429430 =================== =================================================431 ``searchpath`` String with the path to the templates on the432 filesystem.433 ``use_memcache`` Set this to ``True`` to enable memcached caching.434 In that case it behaves like a normal435 `FileSystemLoader` with disabled caching.436 ``memcache_time`` The expire time of a template in the cache.437 ``memcache_host`` a list of memcached servers.438 ``item_prefix`` The prefix for the items on the server. Defaults439 to ``'template/'``.440 =================== =================================================441 """442443 def __init__(self, searchpath, use_memcache=True,444 memcache_time=60 * 60 * 24 * 7, memcache_host=None,445 item_prefix='template/'):446 BaseFileSystemLoader.__init__(self, searchpath)447 MemcachedLoaderMixin.__init__(self, use_memcache, memcache_time,448 memcache_host, item_prefix)449450451class BasePackageLoader(BaseLoader):452 """453 Baseclass for the package loader that does not do any caching.454455 It accepts two parameters: The name of the package and the path relative456 to the package:457458 .. sourcecode:: python459460 from jinja.loaders import BasePackageLoader461462 class MyPackageLoader(BasePackageLoader):463 def __init__(self):464 BasePackageLoader.__init__(self, 'my_package', 'shared/templates')465466 The relative path must use slashes as path delimiters, even on Mac OS467 and Microsoft Windows.468469 It uses the `pkg_resources` libraries distributed with setuptools for470 retrieving the data from the packages. This works for eggs too so you471 don't have to mark your egg as non zip safe.472 """473474 def __init__(self, package_name, package_path):475 try:476 import pkg_resources477 except ImportError:478 raise RuntimeError('setuptools not installed')479 self.package_name = package_name480 self.package_path = package_path481482 def get_source(self, environment, name, parent):483 from pkg_resources import resource_exists, resource_string484 path = '/'.join([self.package_path] + [p for p in name.split('/')485 if p != '..'])486 if not resource_exists(self.package_name, path):487 raise TemplateNotFound(name)488 contents = resource_string(self.package_name, path)489 return contents.decode(environment.template_charset)490491492class PackageLoader(CachedLoaderMixin, BasePackageLoader):493 """494 Loads templates from python packages using setuptools.495496 .. sourcecode:: python497498 from jinja import Environment, PackageLoader499 e = Environment(loader=PackageLoader('yourapp', 'template/path'))500501 You can pass the following keyword arguments to the loader on324 initialisation:502 initialization:503504 =================== =================================================505 ``package_name`` Name of the package containing the templates.506 ``package_path`` Path of the templates inside the package.
31 unmodified lines
538539 def __init__(self, package_name, package_path, use_memcache=False,540 memcache_size=40, cache_folder=None, auto_reload=True,541 cache_salt=None):364 try:365 import pkg_resources366 except ImportError:367 raise RuntimeError('setuptools not installed')368 self.package_name = package_name369 self.package_path = package_path542 BasePackageLoader.__init__(self, package_name, package_path)543544 if cache_salt is None:545 cache_salt = package_name + '/' + package_path546 CachedLoaderMixin.__init__(self, use_memcache, memcache_size,547 cache_folder, auto_reload, cache_salt)548375 def get_source(self, environment, name, parent):376 from pkg_resources import resource_exists, resource_string377 path = '/'.join([self.package_path] + [p for p in name.split('/')378 if p != '..'])379 if not resource_exists(self.package_name, path):380 raise TemplateNotFound(name)381 contents = resource_string(self.package_name, path)382 return contents.decode(environment.template_charset)383549 def check_source_changed(self, environment, name):550 from pkg_resources import resource_exists, resource_filename551 fn = resource_filename(self.package_name, '/'.join([self.package_path] +552 [p for p in name.split('/') if p and p[0] != '.']))
1 unmodified line
554 return path.getmtime(fn)555 return -1556557393class FunctionLoader(CachedLoaderMixin, BaseLoader):558class BaseFunctionLoader(BaseLoader):559 """560 Baseclass for the function loader that doesn't do any caching.561562 It just accepts one parameter which is the function which is called563 with the name of the requested template. If the return value is `None`564 the loader will raise a `TemplateNotFound` error.565566 .. sourcecode:: python567568 from jinja.loaders import BaseFunctionLoader569570 templates = {...}571572 class MyFunctionLoader(BaseFunctionLoader):573 def __init__(self):574 BaseFunctionLoader(templates.get)575 """576577 def __init__(self, loader_func):578 self.loader_func = loader_func579580 def get_source(self, environment, name, parent):581 rv = self.loader_func(name)582 if rv is None:583 raise TemplateNotFound(name)584 if isinstance(rv, str):585 return rv.decode(environment.template_charset)586 return rv587588589class FunctionLoader(CachedLoaderMixin, BaseFunctionLoader):590 """591 Loads templates by calling a function which has to return a string592 or `None` if an error occoured.593594 .. sourcecode:: python
10 unmodified lines
605 templates. Usually you should try to use a loader with a more606 solid backend.607608 You can pass the following keyword arguments to the loader on413 initialisation:609 initialization:610611 =================== =================================================612 ``loader_func`` Function that takes the name of the template to613 load. If it returns a string or unicode object
27 unmodified lines
641642 def __init__(self, loader_func, getmtime_func=None, use_memcache=False,643 memcache_size=40, cache_folder=None, auto_reload=True,644 cache_salt=None):645 BaseFunctionLoader.__init__(self, loader_func)646 # when changing the signature also check the jinja.plugin function647 # loader instantiation.451 self.loader_func = loader_func648 self.getmtime_func = getmtime_func649 if auto_reload and getmtime_func is None:650 auto_reload = False651 CachedLoaderMixin.__init__(self, use_memcache, memcache_size,652 cache_folder, auto_reload, cache_salt)653458 def get_source(self, environment, name, parent):459 rv = self.loader_func(name)460 if rv is None:461 raise TemplateNotFound(name)462 if isinstance(rv, str):463 return rv.decode(environment.template_charset)464 return rv465654 def check_source_changed(self, environment, name):655 return self.getmtime_func(name)656657
67 unmodified lines
modified:jinja/utils.py-1 removed
69 unmodified lines
7071#: function types72callable_types = (FunctionType, MethodType)737474#: number of maximal range items75MAX_RANGE = 10000007677_word_split_re = re.compile(r'(\s+)')
623 unmodified lines
modified:tests/test_syntax.py+6 added
17 unmodified lines
18UNARY = '''{{ +3 }}|{{ -3 }}'''19COMPARE = '''{{ 1 > 0 }}|{{ 1 >= 1 }}|{{ 2 < 3 }}|{{ 2 == 2 }}|{{ 1 <= 1 }}'''20LITERALS = '''{{ [] }}|{{ {} }}|{{ '' }}'''21BOOL = '''{{ true and false }}|{{ false or true }}|{{ not false }}'''22GROUPING = '''{{ (true and false) or (false and true) and not false }}'''232425def test_call():26 from jinja import Environment
55 unmodified lines
8283def test_bool(env):84 tmpl = env.from_string(BOOL)85 assert tmpl.render() == 'False|True|True'868788def test_grouping(env):89 tmpl = env.from_string(GROUPING)90 assert tmpl.render() == 'False'
modified:CHANGES+6 added
110 unmodified lines
111- improved ChoiceLoader error reporting (thanks to Bryan McLemore)112113- fixed extended slicing114115- reworked loader layer. All the cached loaders now have "private" non cached116 baseclasses so that you can easily mix your own caching layers in.117118- added `MemcachedLoaderMixin` and `MemcachedFileSystemLoader` contributed119 by Bryan McLemore.120121122Version 1.0123-----------124(codename: siyutusan, released Mar 23, 2007)125
1 unmodified line
modified:Makefile+3 added
23 unmodified lines
24 @pylint --rcfile scripts/pylintrc jinja2526release: documentation27 @(python2.3 setup.py release bdist_egg upload; python2.4 setup.py release bdist_egg upload; python2.5 setup.py release bdist_egg sdist upload)2829test-release: documentation30 @(python2.3 setup.py release bdist_egg; python2.4 setup.py release bdist_egg; python2.5 setup.py release bdist_egg sdist)