[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
Provenance
- Commit
db69d0a- Tree
110c1b9- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
ecc051b
7 files changed+332 added−52 removed
modified:docs/src/loaders.txt+54 added-2 removed
5 unmodified lines6 7 Builtin Loaders8 ===============9 10+This list contains the builtin loaders you can use without further11+modification:12+13 [[list_of_loaders]]14 15+Loader Baseclasses16+==================17+18+With Jinja 1.1 onwards all the loaders have (except of the uncached) now have19+baseclasses you can use to mix your own caching layer in. This technique is20+explained below. The `BaseLoader` itself is also a loader baseclass but because21+it's the baseclass of each loader it's explained in detail below.22+23+[[list_of_baseloaders]]24+25 Developing Loaders26 ==================27 28 Template loaders are just normal Python classes that have to provide some26 unmodified lines55 finally:56 f.close()57 58 The functions `load` and `parse` which are a requirement for a loader are46-added automatically by the `BaseLoader`.59+added automatically by the `BaseLoader`. Instead of the normal `BaseLoader`60+you can use one of the other base loaders that already come with a proper61+`get_source` method for further modification. Those loaders however are62+new in Jinja 1.1.63 64+CachedLoaderMixin65+-----------------66+67 Additionally to the `BaseLoader` there is a mixin class called68 `CachedLoaderMixin` that implements memory and disk caching of templates.69 Note 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 lines109 You don't have to provide the `check_source_changed` method. If it doesn't110 exist the option `auto_reload` won't have an effect. Also note that the111 `check_source_changed` method must not raise an exception if the template112 does 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 return114+value for not existing templates should be ``-1``.115+116+For the default base classes that come with Jinja 1.1 onwards there exist117+also concrete implementations that support caching. The implementation118+just mixes in the `CachedLoaderMixin`.119+120+MemcachedLoaderMixin121+--------------------122+123+*New in Jinja 1.1*124+125+The `MemcachedLoaderMixin` class adds support for `memcached`_ caching.126+There is only one builtin loader that mixes it in: The127+`MemcachedFileSystemLoader`. If you need other loaders with this mixin128+you can easily subclass one of the existing base loaders. Here an example129+for the `FunctionLoader`:130+131+.. sourcecode:: python132+133+ from jinja.loaders import FunctionLoader, MemcachedLoaderMixin134+135+ class MemcachedFunctionLoader(MemcachedLoaderMixin, FunctionLoader):136+137+ 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+ )145+146+.. _memcached: http://www.danga.com/memcached/modified:docs/generate.py+26 added
99 unmodified lines100 result.append('`%s`\n%s' % (loader.__name__, '\n'.join(doclines)))101 102 return '\n\n'.join(result)103 104+def generate_list_of_baseloaders():105+ from jinja import loaders as loader_module106+107+ 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())119+120+ 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)))125+126+ return '\n\n'.join(result)127+128 def generate_environment_doc():129 from jinja.environment import Environment130 return '%s\n\n%s' % (131 inspect.getdoc(Environment),6 unmodified lines138 139 LIST_OF_FILTERS = generate_list_of_filters()140 LIST_OF_TESTS = generate_list_of_tests()141 LIST_OF_LOADERS = generate_list_of_loaders()142+LIST_OF_BASELOADERS = generate_list_of_baseloaders()143 ENVIRONMENT_DOC = generate_environment_doc()144 CHANGELOG = file(os.path.join(os.path.dirname(__file__), os.pardir, 'CHANGES'))\145 .read().decode('utf-8')146 117 unmodified lines264 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 linesmodified:jinja/loaders.py+237 added-49 removed
3 unmodified lines4 ~~~~~~~~~~~~~5 6 Jinja loader classes.7 8- :copyright: 2007 by Armin Ronacher.8+ :copyright: 2007 by Armin Ronacher, Bryan McLemore.9 :license: BSD, see LICENSE for more details.10 """11 12 import codecs8 unmodified lines21 22 23 #: when updating this, update the listing in the jinja package too24 __all__ = ['FileSystemLoader', 'PackageLoader', 'DictLoader', 'ChoiceLoader',25- 'FunctionLoader']25+ 'FunctionLoader', 'MemcachedFileSystemLoader']26 27 28 def get_template_filename(searchpath, name):29 """111 unmodified lines141 142 143 class 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.148+149+ If the memcaching is enabled you can use (with Jinja 1.1 onwards)150+ the `clear_memcache` function to clear the cache.151+152+ For memcached support check the `MemcachedLoaderMixin`.153 """154 155 def __init__(self, use_memcache, cache_size, cache_folder, auto_reload,156 cache_salt=None):9 unmodified lines166 self.__salt = cache_salt167 self.__times = {}168 self.__lock = Lock()169 170+ def clear_memcache(self):171+ """172+ Clears the memcache.173+ """174+ if self.__memcache is not None:175+ self.__memcache.clear()176+177 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. skip18 unmodified lines206 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 = True44 unmodified lines259 finally:260 self.__lock.release()261 262 250-class FileSystemLoader(CachedLoaderMixin, BaseLoader):263+class MemcachedLoaderMixin(object):264 """265+ Uses a memcached server to cache the templates.266+ """267+268+ 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()284+285+ 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 = False302+303+ # 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 = True311+312+ # 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)316+317+ # 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()325+326+327+class 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.331+332+ How subclassing can work:333+334+ .. sourcecode:: python335+336+ from jinja.loaders import BaseFileSystemLoader337+338+ class MyFileSystemLoader(BaseFileSystemLoader):339+ def __init__(self):340+ BaseFileSystemLoader.__init__(self, '/path/to/templates')341+342+ The base file system loader only takes one parameter beside self which343+ is the path to the templates.344+ """345+346+ def __init__(self, searchpath):347+ self.searchpath = path.abspath(searchpath)348+349+ 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)359+360+361+class FileSystemLoader(CachedLoaderMixin, BaseFileSystemLoader):362+ """363 Loads templates from the filesystem:364 365 .. sourcecode:: python366 367 from jinja import Environment, FileSystemLoader368 e = Environment(loader=FileSystemLoader('templates/'))369 370 You can pass the following keyword arguments to the loader on260- initialisation:371+ initialization:372 373 =================== =================================================374 ``searchpath`` String with the path to the templates on the375 filesystem.21 unmodified lines397 """398 399 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)402+403 if cache_salt is None:404 cache_salt = self.searchpath405 CachedLoaderMixin.__init__(self, use_memcache, memcache_size,406 cache_folder, auto_reload, cache_salt)407 296- 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)306-408 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 -1413 414 314-class PackageLoader(CachedLoaderMixin, BaseLoader):415+class MemcachedFileSystemLoader(MemcachedLoaderMixin, BaseFileSystemLoader):416 """417+ Loads templates from the filesystem and caches them on a memcached418+ server.419+420+ .. sourcecode:: python421+422+ from jinja import Environment, MemcachedFileSystemLoader423+ e = Environment(loader=MemcachedFileSystemLoader('templates/',424+ memcache_host=['192.168.2.250:11211']425+ ))426+427+ You can pass the following keyword arguments to the loader on428+ initialization:429+430+ =================== =================================================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+ """442+443+ 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)449+450+451+class BasePackageLoader(BaseLoader):452+ """453+ Baseclass for the package loader that does not do any caching.454+455+ It accepts two parameters: The name of the package and the path relative456+ to the package:457+458+ .. sourcecode:: python459+460+ from jinja.loaders import BasePackageLoader461+462+ class MyPackageLoader(BasePackageLoader):463+ def __init__(self):464+ BasePackageLoader.__init__(self, 'my_package', 'shared/templates')465+466+ The relative path must use slashes as path delimiters, even on Mac OS467+ and Microsoft Windows.468+469+ 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+ """473+474+ 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_path481+482+ 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)490+491+492+class PackageLoader(CachedLoaderMixin, BasePackageLoader):493+ """494 Loads templates from python packages using setuptools.495 496 .. sourcecode:: python497 498 from jinja import Environment, PackageLoader499 e = Environment(loader=PackageLoader('yourapp', 'template/path'))500 501 You can pass the following keyword arguments to the loader on324- initialisation:502+ initialization:503 504 =================== =================================================505 ``package_name`` Name of the package containing the templates.506 ``package_path`` Path of the templates inside the package.31 unmodified lines538 539 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)543+544 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)548 375- 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)383-549 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 line554 return path.getmtime(fn)555 return -1556 557 393-class FunctionLoader(CachedLoaderMixin, BaseLoader):558+class BaseFunctionLoader(BaseLoader):559 """560+ Baseclass for the function loader that doesn't do any caching.561+562+ 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.565+566+ .. sourcecode:: python567+568+ from jinja.loaders import BaseFunctionLoader569+570+ templates = {...}571+572+ class MyFunctionLoader(BaseFunctionLoader):573+ def __init__(self):574+ BaseFunctionLoader(templates.get)575+ """576+577+ def __init__(self, loader_func):578+ self.loader_func = loader_func579+580+ 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 rv587+588+589+class FunctionLoader(CachedLoaderMixin, BaseFunctionLoader):590+ """591 Loads templates by calling a function which has to return a string592 or `None` if an error occoured.593 594 .. sourcecode:: python10 unmodified lines605 templates. Usually you should try to use a loader with a more606 solid backend.607 608 You can pass the following keyword arguments to the loader on413- initialisation:609+ initialization:610 611 =================== =================================================612 ``loader_func`` Function that takes the name of the template to613 load. If it returns a string or unicode object27 unmodified lines641 642 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)653 458- 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 rv465-654 def check_source_changed(self, environment, name):655 return self.getmtime_func(name)656 657 67 unmodified linesmodified:jinja/utils.py-1 removed
69 unmodified lines70 71 #: function types72 callable_types = (FunctionType, MethodType)73 74-74 #: number of maximal range items75 MAX_RANGE = 100000076 77 _word_split_re = re.compile(r'(\s+)')623 unmodified linesmodified:tests/test_syntax.py+6 added
17 unmodified lines18 UNARY = '''{{ +3 }}|{{ -3 }}'''19 COMPARE = '''{{ 1 > 0 }}|{{ 1 >= 1 }}|{{ 2 < 3 }}|{{ 2 == 2 }}|{{ 1 <= 1 }}'''20 LITERALS = '''{{ [] }}|{{ {} }}|{{ '' }}'''21 BOOL = '''{{ true and false }}|{{ false or true }}|{{ not false }}'''22+GROUPING = '''{{ (true and false) or (false and true) and not false }}'''23 24 25 def test_call():26 from jinja import Environment55 unmodified lines82 83 def test_bool(env):84 tmpl = env.from_string(BOOL)85 assert tmpl.render() == 'False|True|True'86+87+88+def test_grouping(env):89+ tmpl = env.from_string(GROUPING)90+ assert tmpl.render() == 'False'modified:CHANGES+6 added
110 unmodified lines111 - improved ChoiceLoader error reporting (thanks to Bryan McLemore)112 113 - fixed extended slicing114 115+- reworked loader layer. All the cached loaders now have "private" non cached116+ baseclasses so that you can easily mix your own caching layers in.117 118+- added `MemcachedLoaderMixin` and `MemcachedFileSystemLoader` contributed119+ by Bryan McLemore.120+121+122 Version 1.0123 -----------124 (codename: siyutusan, released Mar 23, 2007)125 1 unmodified linemodified:Makefile+3 added
23 unmodified lines24 @pylint --rcfile scripts/pylintrc jinja25 26 release: 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)28+29+test-release: documentation30+ @(python2.3 setup.py release bdist_egg; python2.4 setup.py release bdist_egg; python2.5 setup.py release bdist_egg sdist)