moved caching from loaders to environment and added environment overlays
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 d84ec46 · Browse files · 13 files·+426 added−149 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+426 added−149 removed
- tests:+2 added−2 removed
- other:+424 added−147 removed
Provenance
- Commit
7259c76- Tree
52ab7a1- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
d84ec46
13 files changed+426 added−149 removed
modified:docs/api.rst+166 added-23 removed
46 unmodified lines47 High Level API48 --------------49 50 .. autoclass:: jinja2.environment.Environment51- :members: from_string, get_template, join_path51+ :members: from_string, get_template, join_path, overlay52 53 .. attribute:: shared54 55 If a template was created by using the :class:`Template` constructor10 unmodified lines66 67 .. attribute:: filters68 69 A dict of filters for this environment. As long as no template was70- loaded it's safe to add new filters or remove old.70+ loaded it's safe to add new filters or remove old. For custom filters71+ see :ref:`writing-filters`.72 73 .. attribute:: tests74 75 A dict of test funcitons for this environment. As long as no75- template way loaded it's safe to modify this dict.76+ template way loaded it's safe to modify this dict. For custom tests77+ see :ref:`writing-tests`.78 79 .. attribute:: globals80 81 A dict of global variables. These variables are always available82 in a template and (if the optimizer is enabled) may not be83 override by templates. As long as no template was loaded it's safe82- to modify this dict.84+ to modify this dict. For more details see :ref:`global-namespace`.85 86 87 .. autoclass:: jinja2.Template88 :members: render, stream, generate, module89 90+ .. attribute:: globals91 92+ foo93+94+ .. attribute:: name95+96+ foo97+98+99 .. autoclass:: jinja2.environment.TemplateStream100 :members: disable_buffering, enable_buffering101 102 16 unmodified lines119 120 .. autoclass:: jinja2.runtime.StrictUndefined121 122 123+The Context124+-----------125+126+.. autoclass:: jinja2.runtime.TemplateContext127+ :members: super, get, get_exported, get_all128+129+ .. attribute:: parent130+131+ A dict of read only, global variables the template looks up. These132+ can either come from another :class:`TemplateContext`, from the133+ :attr:`Environment.globals` or :attr:`Template.globals`. It must not134+ be altered.135+136+ .. attribute:: vars137+138+ The template local variables. This list contains environment and139+ context functions from the :attr:`parent` scope as well as local140+ modifications and exported variables from the template. The template141+ will modify this dict during template evaluation but filters and142+ context functions are not allowed to modify it.143+144+ .. attribute:: environment145+146+ The environment that loaded the template.147+148+ .. attribute:: exported_vars149+150+ This set contains all the names the template exports. The values for151+ the names are in the :attr:`vars` dict. In order to get a copy of the152+ exported variables as dict, :meth:`get_exported` can be used.153+154+ .. attribute:: name155+156+ The load name of the template owning this context.157+158+ .. attribute:: blocks159+160+ A dict with the current mapping of blocks in the template. The keys161+ in this dict are the names of the blocks, and the values a list of162+ blocks registered. The last item in each list is the current active163+ block (latest in the inheritance chain).164+165+166 Loaders167 -------168 169 Loaders are responsible for loading templates from a resource such as the117-file system and for keeping the compiled modules in memory. These work like118-Python's `sys.modules` which keeps the imported templates in memory. Unlike119-`sys.modules` however this cache is limited in size by default and templates120-are automatically reloaded. Each loader that extends :class:`BaseLoader`121-supports this caching and accepts two parameters to configure it:170+file system. The environment will keep the compiled modules in memory like171+Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in172+size by default and templates are automatically reloaded.173 123-`cache_size`124- The size of the cache. Per default this is ``50`` which means that if125- more than 50 templates are loaded the loader will clean out the least126- recently used template. If the cache size is set to ``0`` templates are127- recompiled all the time, if the cache size is ``-1`` the cache will not128- be cleaned.129-130-`auto_reload`131- Some loaders load templates from locations where the template sources132- may change (ie: file system or database). If `auto_reload` is set to133- `True` (default) every time a template is requested the loader checks134- if the source changed and if yes, it will reload the template. For135- higher performance it's possible to disable that.136-174 .. autoclass:: jinja2.loaders.FileSystemLoader175 176 .. autoclass:: jinja2.loaders.PackageLoader177 47 unmodified lines225 226 .. autoclass:: jinja2.exceptions.TemplateSyntaxError227 228 .. autoclass:: jinja2.exceptions.TemplateAssertionError229+230+231+.. _writing-filters:232+233+Custom Filters234+--------------235+236+Custom filters are just regular Python functions that take the left side of237+the filter as first argument and the the arguments passed to the filter as238+extra arguments or keyword arguments.239+240+For example in the filter ``{{ 42|myfilter(23) }}`` the function would be241+called with ``myfilter(42, 23)``. Here for example a simple filter that can242+be applied to datetime objects to format them::243+244+ def datetimeformat(value, format='%H:%M / %d-%m-%Y'):245+ return value.strftime(format)246+247+You can register it on the template environment by updating the248+:attr:`~Environment.filters` dict on the environment::249+250+ environment.filters['datetimeformat'] = datetimeformat251+252+Inside the template it can then be used as follows:253+254+.. sourcecode:: jinja255+256+ written on: {{ article.pub_date|datetimeformat }}257+ publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}258+259+Filters can also be passed the current template context or environment. This260+is useful if a filters wants to return an undefined value or check the current261+:attr:`~Environment.autoescape` setting. For this purpose two decorators262+exist: :func:`environmentfilter` and :func:`contextfilter`.263+264+Here a small example filter that breaks a text into HTML line breaks and265+paragraphs and marks the return value as safe HTML string if autoescaping is266+enabled::267+268+ import re269+ from jinja2 import environmentfilter, Markup, escape270+271+ _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')272+273+ @environmentfilter274+ def nl2br(environment, value):275+ result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')276+ for p in _paragraph_re.split(escape(value)))277+ if environment.autoescape:278+ result = Markup(result)279+ return result280+281+Context filters work the same just that the first argument is the current282+active :class:`TemplateContext` rather then the environment.283+284+285+.. _writing-tests:286+287+Custom Tests288+------------289+290+Tests work like filters just that there is no way for a filter to get access291+to the environment or context and that they can't be chained. The return292+value of a filter should be `True` or `False`. The purpose of a filter is to293+give the template designers the possibility to perform type and conformability294+checks.295+296+Here a simple filter that checks if a variable is a prime number::297+298+ import math299+300+ def is_prime(n):301+ if n == 2:302+ return True303+ for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):304+ if n % i == 0:305+ return False306+ return True307+ 308+309+You can register it on the template environment by updating the310+:attr:`~Environment.tests` dict on the environment::311+312+ environment.tests['prime'] = is_prime313+314+A template designer can then use the test like this:315+316+.. sourcecode:: jinja317+318+ {% if 42 is prime %}319+ 42 is a prime number320+ {% else %}321+ 42 is not a prime number322+ {% endif %}323+324+325+.. _global-namespace:326+327+The Global Namespace328+--------------------329+330+Variables stored in the :attr:`Environment.globals` or :attr:`Template.globals`331+dicts are special as they are available for imported templates too and will be332+used by the optimizer in future releases to evaluates parts of the template at333+compile time. This is the place where you can put variables and functions334+that should be available all the time.modified:docs/conf.py+1 added-1 removed
135 unmodified lines136 \usepackage{palatino}137 \definecolor{TitleColor}{rgb}{0.7,0,0}138 \definecolor{InnerLinkColor}{rgb}{0.7,0,0}139 \definecolor{OuterLinkColor}{rgb}{0.8,0,0}140-\definecolor{VerbatimColor}{rgb}{0.98,0.98,0.98}140+\definecolor{VerbatimColor}{rgb}{0.985,0.985,0.985}141 \definecolor{VerbatimBorderColor}{rgb}{0.8,0.8,0.8}142 '''143 144 # Documents to append as an appendix to all manuals.4 unmodified linesmodified:docs/jinjaext.py+1 added-1 removed
41 unmodified lines42 Name.Attribute: '#686868',43 Name.Tag: 'bold #686868',44 Name.Decorator: '#686868',45 46- String: '#BE9B5D',46+ String: '#AA891C',47 Number: '#444444',48 49 Generic.Heading: 'bold #000080',50 Generic.Subheading: 'bold #800080',72 unmodified linesmodified:docs/templates.rst+21 added
780 unmodified lines781 List of Builtin Tests782 ---------------------783 784 .. jinjatests::785+786+787+List of Global Functions788+------------------------789+790+The following functions are available in the global scope by default:791+792+.. function:: range([start,] stop[, step])793+794+ Return a list containing an arithmetic progression of integers.795+ range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.796+ When step is given, it specifies the increment (or decrement).797+ For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!798+ These are exactly the valid indices for a list of 4 elements.799+800+.. function:: lipsum(n=5, html=True, min=20, max=100)801+802+ Generates some lorem ipsum for the template. Per default five paragraphs803+ with HTML are generated each paragraph between 20 and 100 words. If html804+ is disabled regular text is returned. This is useful to generate simple805+ contents for layout testing.modified:jinja2/__init__.py+10 added
48 unmodified lines49 50 # decorators and public utilities51 from jinja2.filters import environmentfilter, contextfilter52 from jinja2.utils import Markup, escape, environmentfunction, contextfunction53+54+__all__ = [55+ 'Environment', 'Template', 'BaseLoader', 'FileSystemLoader',56+ 'PackageLoader', 'DictLoader', 'FunctionLoader', 'PrefixLoader',57+ 'ChoiceLoader', 'Undefined', 'DebugUndefined', 'StrictUndefined',58+ 'TemplateError', 'UndefinedError', 'TemplateNotFound',59+ 'TemplateSyntaxError', 'TemplateAssertionError', 'environmentfilter',60+ 'contextfilter', 'Markup', 'escape', 'environmentfunction',61+ 'contextfunction'62+]modified:jinja2/defaults.py+13 added
11 unmodified lines12 from jinja2.tests import TESTS as DEFAULT_TESTS13 from jinja2.utils import generate_lorem_ipsum14 15 16+BLOCK_START_STRING = '{%'17+BLOCK_END_STRING = '%}'18+VARIABLE_START_STRING = '{{'19+VARIABLE_END_STRING = '}}'20+COMMENT_START_STRING = '{#'21+COMMENT_END_STRING = '#}'22+LINE_STATEMENT_PREFIX = None23+24+25 DEFAULT_NAMESPACE = {26 'range': xrange,27 'lipsum': generate_lorem_ipsum28 }29+30+31+# export all constants32+__all__ = tuple(x for x in locals() if x.isupper())modified:jinja2/environment.py+147 added-50 removed
7 unmodified lines8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import sys12+from jinja2.defaults import *13 from jinja2.lexer import Lexer14 from jinja2.parser import Parser15 from jinja2.optimizer import optimize16 from jinja2.compiler import generate17 from jinja2.runtime import Undefined, TemplateContext, concat18 from jinja2.debug import translate_exception18-from jinja2.utils import import_string, LRUCache, Markup19-from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE19+from jinja2.utils import import_string, LRUCache, Markup, missing20 21 22 # for direct template usage we have up to ten living environments23 _spontaneous_environments = LRUCache(10)14 unmodified lines38 env.shared = True39 return env40 41 42-def template_from_code(environment, code, globals, uptodate=None,43- template_class=None):44- """Generate a new template object from code. It's used in the45- template constructor and the loader `load` implementation.42+def create_cache(size):43+ """Return the cache class for the given size."""44+ if size == 0:45+ return None46+ if size < 0:47+ return {}48+ return LRUCache(size)49+50+51+def load_extensions(environment, extensions):52+ """Load the extensions from the list and bind it to the environment.53+ Returns a new list of instanciated environments.54 """47- t = object.__new__(template_class or environment.template_class)48- namespace = {49- 'environment': environment,50- '__jinja_template__': t51- }52- exec code in namespace53- t.environment = environment54- t.name = namespace['name']55- t.filename = code.co_filename56- t.root_render_func = namespace['root']57- t.blocks = namespace['blocks']58- t.globals = globals55+ result = []56+ for extension in extensions:57+ if isinstance(extension, basestring):58+ extension = import_string(extension)59+ result.append(extension(environment))60+ return result61 60- # debug and loader helpers61- t._debug_info = namespace['debug_info']62- t._uptodate = uptodate62 64- return t63+def _environment_sanity_check(environment):64+ """Perform a sanity check on the environment."""65+ assert issubclass(environment.undefined, Undefined), 'undefined must ' \66+ 'be a subclass of undefined because filters depend on it.'67+ assert environment.block_start_string != \68+ environment.variable_start_string != \69+ environment.comment_start_string, 'block, variable and comment ' \70+ 'start strings must be different'71 72 73 class Environment(object):74 """The core component of Jinja is the `Environment`. It contains48 unmodified lines123 If set to true the XML/HTML autoescaping feature is enabled.124 125 `loader`126 The template loader for this environment.127+128+ `cache_size`129+ The size of the cache. Per default this is ``50`` which means that if130+ more than 50 templates are loaded the loader will clean out the least131+ recently used template. If the cache size is set to ``0`` templates are132+ recompiled all the time, if the cache size is ``-1`` the cache will not133+ be cleaned.134+135+ `auto_reload`136+ Some loaders load templates from locations where the template sources137+ may change (ie: file system or database). If `auto_reload` is set to138+ `True` (default) every time a template is requested the loader checks139+ if the source changed and if yes, it will reload the template. For140+ higher performance it's possible to disable that.141 """142 143 #: if this environment is sandboxed. Modifying this variable won't make144 #: the environment sandboxed though. For a real sandboxed environment145 #: have a look at jinja2.sandbox146 sandboxed = False147 148+ #: True if the environment is just an overlay149+ overlay = False150+151 #: shared environments have this set to `True`. A shared environment152 #: must not be modified153 shared = False154 155 def __init__(self,133- block_start_string='{%',134- block_end_string='%}',135- variable_start_string='{{',136- variable_end_string='}}',137- comment_start_string='{#',138- comment_end_string='#}',139- line_statement_prefix=None,156+ block_start_string=BLOCK_START_STRING,157+ block_end_string=BLOCK_END_STRING,158+ variable_start_string=VARIABLE_START_STRING,159+ variable_end_string=VARIABLE_END_STRING,160+ comment_start_string=COMMENT_START_STRING,161+ comment_end_string=COMMENT_END_STRING,162+ line_statement_prefix=LINE_STATEMENT_PREFIX,163 trim_blocks=False,164 extensions=(),165 optimized=True,166 undefined=Undefined,167 finalize=None,168 autoescape=False,146- loader=None):169+ loader=None,170+ cache_size=50,171+ auto_reload=True):172 # !!Important notice!!173 # The constructor accepts quite a few arguments that should be174 # passed by keyword rather than position. However it's important to175 # not change the order of arguments because it's used at least1 unmodified line177 # - spontaneus environments (i18n extension and Template)178 # - unittests179 # If parameter changes are required only add parameters at the end180 # and don't change the arguments (or the defaults!) of the arguments156- # up to (but excluding) loader.181+ # existing already.182 158- # santity checks159- assert issubclass(undefined, Undefined), 'undefined must be ' \160- 'a subclass of undefined because filters depend on it.'161- assert block_start_string != variable_start_string != \162- comment_start_string, 'block, variable and comment ' \163- 'start strings must be different'164-183 # lexer / parser information184 self.block_start_string = block_start_string185 self.block_end_string = block_end_string186 self.variable_start_string = variable_start_string15 unmodified lines202 self.globals = DEFAULT_NAMESPACE.copy()203 204 # set the loader provided205 self.loader = loader206+ self.cache = create_cache(cache_size)207+ self.auto_reload = auto_reload208 189- # create lexer190- self.lexer = Lexer(self)191-209 # load extensions193- self.extensions = []194- for extension in extensions:195- if isinstance(extension, basestring):196- extension = import_string(extension)197- self.extensions.append(extension(self))210+ self.extensions = load_extensions(self, extensions)211 212+ _environment_sanity_check(self)213+214+ def overlay(self, block_start_string=missing, block_end_string=missing,215+ variable_start_string=missing, variable_end_string=missing,216+ comment_start_string=missing, comment_end_string=missing,217+ line_statement_prefix=missing, trim_blocks=missing,218+ extensions=missing, optimized=missing, undefined=missing,219+ finalize=missing, autoescape=missing, loader=missing,220+ cache_size=missing, auto_reload=missing):221+ """Create a new overlay environment that shares all the data with the222+ current environment except of cache and the overriden attributes.223+ Extensions cannot be removed for a overlayed environment. A overlayed224+ environment automatically gets all the extensions of the environment it225+ is linked to plus optional extra extensions.226+227+ Creating overlays should happen after the initial environment was set228+ up completely. Not all attributes are truly linked, some are just229+ copied over so modifications on the original environment may not shine230+ through.231+ """232+ args = dict(locals())233+ del args['self'], args['cache_size'], args['extensions']234+235+ rv = object.__new__(self.__class__)236+ rv.__dict__.update(self.__dict__)237+ rv.overlay = True238+ rv.linked_to = self239+240+ for key, value in args.iteritems():241+ if value is not missing:242+ setattr(rv, key, value)243+244+ if cache_size is not missing:245+ rv.cache = create_cache(cache_size)246+247+ rv.extensions = []248+ for extension in self.extensions:249+ rv.extensions.append(extension.bind(self))250+ if extensions is not missing:251+ rv.extensions.extend(load_extensions(extensions))252+253+ _environment_sanity_check(rv)254+ return rv255+256+ @property257+ def lexer(self):258+ """Return a fresh lexer for the environment."""259+ return Lexer(self)260+261 def subscribe(self, obj, argument):262 """Get an item or attribute of an object."""263 try:264 return getattr(obj, str(argument))75 unmodified lines340 if self.loader is None:341 raise TypeError('no loader for this environment specified')342 if parent is not None:343 name = self.join_path(name, parent)282- return self.loader.load(self, name, self.make_globals(globals))344 345+ if self.cache is not None:346+ template = self.cache.get(name)347+ if template is not None and (not self.auto_reload or \348+ template.is_up_to_date):349+ return template350+351+ template = self.loader.load(self, name, self.make_globals(globals))352+ if self.cache is not None:353+ self.cache[name] = template354+ return template355+356 def from_string(self, source, globals=None, template_class=None):357 """Load a template from a string. This parses the source given and358 returns a :class:`Template` object.359 """360 globals = self.make_globals(globals)361+ cls = template_class or self.template_class289- return template_from_code(self, self.compile(source, globals=globals),290- globals, None, template_class)362+ return cls.from_code(self, self.compile(source, globals=globals),363+ globals, None)364 365 def make_globals(self, d):366 """Return a dict for the globals."""367 if d is None:49 unmodified lines417 env = get_spontaneous_environment(418 block_start_string, block_end_string, variable_start_string,419 variable_end_string, comment_start_string, comment_end_string,420 line_statement_prefix, trim_blocks, tuple(extensions), optimized,348- undefined, finalize, autoescape)421+ undefined, finalize, autoescape, None, 0, False)422 return env.from_string(source, template_class=cls)423 424+ @classmethod425+ def from_code(cls, environment, code, globals, uptodate=None):426+ """Creates a template object from compiled code and the globals. This427+ is used by the loaders and environment to create a template object.428+ """429+ t = object.__new__(cls)430+ namespace = {431+ 'environment': environment,432+ '__jinja_template__': t433+ }434+ exec code in namespace435+ t.environment = environment436+ t.name = namespace['name']437+ t.filename = code.co_filename438+ t.root_render_func = namespace['root']439+ t.blocks = namespace['blocks']440+ t.globals = globals441+442+ # debug and loader helpers443+ t._debug_info = namespace['debug_info']444+ t._uptodate = uptodate445+446+ return t447+448 def render(self, *args, **kwargs):449 """This method accepts the same arguments as the `dict` constructor:450 A dict, a dict subclass or some keyword arguments. If no arguments451 are given the context will be empty. These two calls do the same::202 unmodified linesmodified:jinja2/ext.py+18 added-3 removed
24 unmodified lines25 GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')26 27 28 class Extension(object):29- """Instances of this class store parser extensions."""29+ """Extensions can be used to add extra functionality to the Jinja template30+ system at the parser level. This is a supported but currently31+ undocumented interface. Custom extensions are bound to an environment but32+ may not store environment specific data on `self`. The reason for this is33+ that an extension can be bound to another environment (for overlays) by34+ creating a copy and reassigning the `environment` attribute.35+ """36 37 #: if this extension parses this is the list of tags it's listening to.38 tags = set()39 40 def __init__(self, environment):41 self.environment = environment42 43+ def bind(self, environment):44+ """Create a copy of this extension bound to another environment."""45+ rv = object.__new__(self.__class__)46+ rv.__dict__.update(self.__dict__)47+ rv.environment = environment48+ return rv49+50 def parse(self, parser):51 """Called if one of the tags matched."""52 53 247 unmodified lines301 options.get('line_statement_prefix') or None,302 options.get('trim_blocks', '').lower() in ('1', 'on', 'yes', 'true'),303 tuple(extensions),304 # fill with defaults so that environments are shared292- # with other spontaneus environments.293- True, Undefined, None, False305+ # with other spontaneus environments. The rest of the306+ # arguments are optimizer, undefined, finalize, autoescape,307+ # loader, cache size and auto reloading setting308+ True, Undefined, None, False, None, 0, False309 )310 311 node = environment.parse(fileobj.read().decode(encoding))312 for lineno, func, message in extract_from_ast(node, keywords):1 unmodified linemodified:jinja2/loaders.py+16 added-40 removed
3 unmodified lines4 ~~~~~~~~~~~~~~5 6 Jinja loader classes.7 8+ XXX: move caching from the loaders to environment.get_template and add9+ environment overlays that allow to redefine escaping and other things but10+ shared the globals and filter mappings.11+12 :copyright: 2008 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14 """15 from os import path16 from jinja2.exceptions import TemplateNotFound13-from jinja2.environment import template_from_code17 from jinja2.utils import LRUCache18 19 20 def split_template_path(template):38 unmodified lines59 source = f.read().decode('utf-8')60 return source, path, lambda: mtime != getmtime(path)61 """62 60- def __init__(self, cache_size=50, auto_reload=True):61- if cache_size == 0:62- self.cache = None63- elif cache_size < 0:64- self.cache = {}65- else:66- self.cache = LRUCache(cache_size)67- self.auto_reload = auto_reload68-63 def get_source(self, environment, template):64 """Get the template source, filename and reload helper for a template.65 It's passed the environment and template name and has to return a66 tuple in the form ``(source, filename, uptodate)`` or raise a21 unmodified lines88 will not call this method but `get_source` directly.89 """90 if globals is None:91 globals = {}98-99- if self.cache is not None:100- template = self.cache.get(name)101- if template is not None and (not self.auto_reload or \102- template.is_up_to_date):103- return template104-92 source, filename, uptodate = self.get_source(environment, name)93 code = environment.compile(source, name, filename, globals)107- template = template_from_code(environment, code, globals, uptodate)108- if self.cache is not None:109- self.cache[name] = template110- return template94+ return environment.template_class.from_code(environment, code,95+ globals, uptodate)96 97 98 class FileSystemLoader(BaseLoader):99 """Loads templates from the file system. This loader can find templates9 unmodified lines109 Per default the template encoding is ``'utf-8'`` which can be changed110 by setting the `encoding` parameter to something else.111 """112 128- def __init__(self, searchpath, encoding='utf-8', cache_size=50,129- auto_reload=True):130- BaseLoader.__init__(self, cache_size, auto_reload)113+ def __init__(self, searchpath, encoding='utf-8'):114 if isinstance(searchpath, basestring):115 searchpath = [searchpath]116 self.searchpath = list(searchpath)117 self.encoding = encoding29 unmodified lines147 from the file system and not a zip file.148 """149 150 def __init__(self, package_name, package_path='templates',168- encoding='utf-8', cache_size=50, auto_reload=True):169- BaseLoader.__init__(self, cache_size, auto_reload)151+ encoding='utf-8'):152 from pkg_resources import DefaultProvider, ResourceManager, get_provider153 provider = get_provider(package_name)154 self.encoding = encoding155 self.manager = ResourceManager()26 unmodified lines182 183 Because auto reloading is rarely useful this is disabled per default.184 """185 204- def __init__(self, mapping, cache_size=50, auto_reload=False):205- BaseLoader.__init__(self, cache_size, auto_reload)186+ def __init__(self, mapping):187 self.mapping = mapping188 189 def get_source(self, environment, template):190 if template in self.mapping:19 unmodified lines210 details have a look at :meth:`BaseLoader.get_source` which has the same211 return value.212 """213 233- def __init__(self, load_func, cache_size=50, auto_reload=True):234- BaseLoader.__init__(self, cache_size, auto_reload)214+ def __init__(self, load_func):215 self.load_func = load_func216 217 def get_source(self, environment, template):218 rv = self.load_func(template)5 unmodified lines224 225 226 class PrefixLoader(BaseLoader):227 """A loader that is passed a dict of loaders where each loader is bound248- to a prefix. The caching is independent of the actual loaders so the249- per loader cache settings are ignored. The prefix is delimited from the250- template by a slash:228+ to a prefix. The prefix is delimited from the template by a slash per229+ default, which can be changed by setting the `delimiter` argument to230+ something else.231 232 >>> loader = PrefixLoader({233 ... 'app1': PackageLoader('mypackage.app1'),234 ... 'app2': PackageLoader('mypackage.app2')2 unmodified lines237 By loading ``'app1/index.html'`` the file from the app1 package is loaded,238 by loading ``'app2/index.html'`` the file from the second.239 """240 261- def __init__(self, mapping, delimiter='/', cache_size=50,262- auto_reload=True):263- BaseLoader.__init__(self, cache_size, auto_reload)241+ def __init__(self, mapping, delimiter='/'):242 self.mapping = mapping243 self.delimiter = delimiter244 245 def get_source(self, environment, template):7 unmodified lines253 254 class ChoiceLoader(BaseLoader):255 """This loader works like the `PrefixLoader` just that no prefix is256 specified. If a template could not be found by one loader the next one279- is tried. Like for the `PrefixLoader` the cache settings of the actual280- loaders don't matter as the choice loader does the caching.257+ is tried.258 259 >>> loader = ChoiceLoader([260 ... FileSystemLoader('/path/to/user/templates'),261 ... PackageLoader('myapplication')2 unmodified lines264 This is useful if you want to allow users to override builtin templates265 from a different location.266 """267 291- def __init__(self, loaders, cache_size=50, auto_reload=True):292- BaseLoader.__init__(self, cache_size, auto_reload)268+ def __init__(self, loaders):269 self.loaders = loaders270 271 def get_source(self, environment, template):272 for loader in self.loaders:5 unmodified linesmodified:jinja2/runtime.py+24 added-27 removed
9 unmodified lines10 """11 import sys12 from types import FunctionType13 from itertools import chain, imap14-from jinja2.utils import Markup, partial, soft_unicode, escape14+from jinja2.utils import Markup, partial, soft_unicode, escape, missing15 from jinja2.exceptions import UndefinedError, TemplateRuntimeError16 17 18 # these variables are exported to the template runtime1 unmodified line20 'TemplateRuntimeError', 'Markup', 'missing', 'concat', 'escape',21 'markup_join', 'unicode_join']22 23 24-# special singleton representing missing values for the runtime25-missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()26-27-24 # concatenate a list of strings and convert them to unicode.25 # unfortunately there is a bug in python 2.4 and lower that causes26 # unicode.join trash the traceback.27 try:28 def _test_gen_bug():29 raise TypeError(_test_gen_bug)30 yield None31 u''.join(_test_gen_bug())36-except TypeError, e:37- if e.args and e.args[0] is _test_gen_bug:32+except TypeError, _error:33+ if _error.args and _error.args[0] is _test_gen_bug:34 concat = u''.join35 else:36 def concat(gen):37 try:38 return u''.join(list(gen))39 except:40 exc_type, exc_value, tb = sys.exc_info()41 raise exc_type, exc_value, tb.tb_next46-del _test_gen_bug42+ del _test_gen_bug, _error43 44 45 def markup_join(*args):46 """Concatenation that escapes if necessary and converts to unicode."""11 unmodified lines58 return concat(imap(unicode, args))59 60 61 class TemplateContext(object):66- """Holds the variables of the local template or of the global one. It's67- not save to use this class outside of the compiled code. For example68- update and other methods will not work as they seem (they don't update69- the exported variables for example).62+ """The template context holds the variables of a template. It stores the63+ values passed to the template and also the names the template exports.64+ Creating instances is neither supported nor useful as it's created65+ automatically at various stages of the template evaluation and should not66+ be created by hand.67 71- The context is immutable. Modifications on `parent` must not happen and72- modifications on `vars` are allowed from generated template code. However73- functions that are passed the template context may not modify the context74- in any way.68+ The context is immutable. Modifications on :attr:`parent` **must not**69+ happen and modifications on :attr:`vars` are allowed from generated70+ template code only. Template filters and global functions marked as71+ :func:`contextfunction`\s get the active context passed as first argument72+ and are allowed to access the context read-only.73+74+ The template context supports read only dict operations (`get`,75+ `__getitem__`, `__contains__`) however `__getitem__` doesn't fail with76+ a `KeyError` but returns an :attr:`Undefined` object.77 """78 79 def __init__(self, environment, parent, name, blocks):80 self.parent = parent30 unmodified lines111 render.__name__ = render.name = name112 return render113 114 def get(self, key, default=None):113- """For dict compatibility"""115+ """Returns an item from the template context, if it doesn't exist116+ `default` is returned.117+ """118 if key in self.vars:119 return self.vars[key]120 if key in self.parent:121 return self.parent[key]2 unmodified lines124 def get_exported(self):125 """Get a new dict with the exported variables."""126 return dict((k, self.vars[k]) for k in self.exported_vars)127 124- def get_root(self):125- """Return a new dict with all the non local variables."""126- return dict(self.parent)127-128 def get_all(self):129- """Return a copy of the complete context as dict."""129+ """Return a copy of the complete context as dict including the130+ global variables.131+ """132 return dict(self.parent, **self.vars)133 132- def clone(self):133- """Return a copy of the context without the locals."""134- return self.__class__(self.environment, self.parent,135- self.name, self.blocks)136-134 def __contains__(self, name):135 return name in self.vars or name in self.parent136 137 def __getitem__(self, key):268 unmodified linesmodified:jinja2/utils.py+4 added
23 unmodified lines24 )25 _simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')26 27 28+# special singleton representing missing values for the runtime29+missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()30+31+32 def contextfunction(f):33 """This decorator can be used to mark a callable as context callable. A34 context callable is passed the active context as first argument if it35 was directly stored in the context.398 unmodified linesmodified:tests/conftest.py+2 added-2 removed
61 unmodified lines62 except KeyError:63 raise TemplateNotFound(name)64 65 66-loader = GlobalLoader(cache_size=0)67-simple_env = Environment(trim_blocks=True, loader=loader)66+loader = GlobalLoader()67+simple_env = Environment(trim_blocks=True, loader=loader, cache_size=0)68 69 70 class Module(py.test.collect.Module):71 37 unmodified linesmodified:.hgignore+3 added-2 removed
1 ^instance$2 ^instance/3-^jinja/.*\.so$4-^(build|dist|Jinja\.egg-info)/3+^jinja2/.*\.so$4+^docs/_.*5+^(build|dist|Jinja2\.egg-info)/6 \.py[co]$7 \.DS_Store$