Skip to content
Myr

a clean restart

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk rename : jinja/__init__.py => jinja2/__init__.py rename : jinja/_debugger.c => jinja2/_debugger.c rename : jinja/_native.py => jinja2/_native.py rename : jinja/_speedups.c => jinja2/_speedups.c rename : jinja/constants.py => jinja2/constants.py rename : jinja/contrib/__init__.py => jinja2/contrib/__init__.py rename : jinja/contrib/_djangosupport.py => jinja2/contrib/_djangosupport.py rename : jinja/contrib/djangosupport.py => jinja2/contrib/djangosupport.py rename : jinja/datastructure.py => jinja2/datastructure.py rename : jinja/defaults.py => jinja2/defaults.py rename : jinja/environment.py => jinja2/environment.py rename : jinja/exceptions.py => jinja2/exceptions.py rename : jinja/filters.py => jinja2/filters.py rename : jinja/lexer.py => jinja2/lexer.py rename : jinja/loaders.py => jinja2/loaders.py rename : jinja/nodes.py => jinja2/nodes.py rename : jinja/parser.py => jinja2/parser.py rename : jinja/tests.py => jinja2/tests.py rename : jinja/translators/__init__.py => jinja2/translators/__init__.py rename : jinja/translators/python.py => jinja2/translators/python.py rename : jinja/utils.py => jinja2/utils.py

authored by Armin Ronacher · committed by Armin Ronacher · parent e074cd2 · Browse files · 44 files+4721 added−8942 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

44 files+4721 added−8942 removed

  • other:+4721 added−8942 removed

44 files+4721 added−8942 removed

deleted:jinja/contrib/__init__.py-11 removed
1# -*- coding: utf-8 -*-2"""3 jinja.contrib4 ~~~~~~~~~~~~~56 This module collections various third-party helper functions and classes7 that are useful for frameworks etc.89 :copyright: 2007 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""
deleted:jinja/contrib/_djangosupport.py-209 removed
1# -*- coding: utf-8 -*-2"""3 jinja.contrib._djangosupport4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 Django suport layer. This module is a metamodule, do never import it7 directly or access any of the functions defined here.89 The public interface is `jinja.contrib.djangosupport` and10 `django.contrib.jinja`. See the docstring of `jinja.contrib.djangosupport`11 for more details.1213 :copyright: 2007-2008 by Armin Ronacher, Bryan McLemore, David Cramer.14 :license: BSD, see LICENSE for more details.15"""16import sys17import warnings18import new19from django.conf import settings20from django.template.context import get_standard_processors21from django.http import HttpResponse22from django import contrib2324from jinja import Environment, FileSystemLoader, ChoiceLoader25from jinja.loaders import MemcachedFileSystemLoader262728exported = ['render_to_response', 'render_to_string', 'convert_django_filter']293031#: used environment32env = None333435#: default filters36DEFAULT_FILTERS = (37 'django.template.defaultfilters.date',38 'django.template.defaultfilters.timesince',39 'django.template.defaultfilters.linebreaks',40 'django.contrib.humanize.templatetags.humanize.intcomma'41)4243def configure(convert_filters=DEFAULT_FILTERS, loader=None, **options):44 """45 Initialize the system.46 """47 global env4849 if env:50 warnings.warn("Jinja already initialized.")51 return5253 # setup environment54 if loader is None:55 loaders = tuple(FileSystemLoader(l) for l in settings.TEMPLATE_DIRS)56 if not loaders:57 loader = None58 elif len(loaders) == 1:59 loader = loaders[0]60 else:61 loader = ChoiceLoader(loaders)62 env = Environment(loader=loader, **options)6364 # convert requested filters65 for name in convert_filters:66 env.filters[name] = convert_django_filter(name)6768 # import templatetags of installed apps69 for app in settings.INSTALLED_APPS:70 try:71 __import__(app + '.templatetags')72 except ImportError:73 pass7475 # setup the django.contrib.jinja module76 setup_django_module()777879def setup_django_module():80 """81 create a new Jinja module for django.82 """83 from jinja.contrib import djangosupport84 module = contrib.jinja = sys.modules['django.contrib.jinja'] = \85 new.module('django.contrib.jinja')86 module.env = env87 module.__doc__ = djangosupport.__doc__88 module.register = Library89 public_names = module.__all__ = ['register', 'env']90 get_name = globals().get91 for name in exported:92 setattr(module, name, get_name(name))93 public_names.append(name)949596def render_to_response(template, context={}, request=None,97 mimetype=None):98 """This function will take a few variables and spit out a full webpage."""99 content = render_to_string(template, context, request)100 if mimetype is None:101 mimetype = settings.DEFAULT_CONTENT_TYPE102 return HttpResponse(content, mimetype)103104105def render_to_string(template, context={}, request=None):106 """Render a template to a string."""107 assert env is not None, 'Jinja not configured for django'108 if request is not None:109 context['request'] = request110 for processor in get_standard_processors():111 context.update(processor(request))112 template = env.get_template(template)113 return template.render(context)114115116def convert_django_filter(f):117 """Convert a django filter into a Jinja filter."""118 if isinstance(f, str):119 p = f.split('.')120 f = getattr(__import__('.'.join(p[:-1]), None, None, ['']), p[-1])121 def filter_factory(*args):122 def wrapped(env, ctx, value):123 return f(value, *args)124 return wrapped125 filter_factory.__name__ = f.__name__126 filter_factory.__doc__ = getattr(f, '__doc__', None)127 return filter_factory128129130class Library(object):131 """132 Continues a general feel of wrapping all the registration133 methods for easy importing.134135 This is available in `django.contrib.jinja` as `register`.136137 For more details see the docstring of the `django.contrib.jinja` module.138 """139 def object(func, name=None):140 """Register a new global."""141 if name is None:142 name = getattr(func, '__name__')143 env.globals[name] = func144 return func145 object = staticmethod(object)146147 def filter(func, name=None):148 """Register a new filter function."""149 if name is None:150 name = func.__name__151 env.filters[name] = func152 return func153 filter = staticmethod(filter)154155 def test(func, name):156 """Register a new test function."""157 if name is None:158 name = func.__name__159 env.tests[name] = func160 return func161 test = staticmethod(test)162163 def context_inclusion(func, template, name=None):164 """165 Similar to the inclusion tag from django this one expects func to be a166 function with a similar argument list to func(context, *args, **kwargs)167168 It passed in the current context allowing the function to edit it or read169 from it. the function must return a dict with which to pass into the170 renderer. Normally expected is an altered dictionary.171172 Note processors are NOT ran on this context.173 """174 def wrapper(env, context, *args, **kwargs):175 context = func(context.to_dict(), *args, **kwargs)176 return render_to_string(template, context)177 wrapper.jinja_context_callable = True178 if name is None:179 name = func.__name__180 try:181 wrapper.__name__ = func.__name__182 wrapper.__doc__ = func.__doc__183 except:184 pass185 env.globals[name] = wrapper186 context_inclusion = staticmethod(context_inclusion)187188 def clean_inclusion(func, template, name=None, run_processors=False):189 """190 Similar to above however it won't pass the context into func().191 Also the returned context will have the context processors run upon it.192 """193 def wrapper(env, context, *args, **kwargs):194 if run_processors:195 request = context['request']196 else:197 request = None198 context = func({}, *args, **kwargs)199 return render_to_string(template, context, request)200 wrapper.jinja_context_callable = True201 if name is None:202 name = func.__name__203 try:204 wrapper.__name__ = func.__name__205 wrapper.__doc__ = func.__doc__206 except:207 pass208 env.globals[name] = wrapper209 clean_inclusion = staticmethod(clean_inclusion)
deleted:jinja/contrib/djangosupport.py-124 removed
1# -*- coding: utf-8 -*-2"""3 jinja.contrib.djangosupport4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~56 Support for the django framework. This module is quite magical because it7 just exports one single function, the `configure` function which is used8 to create a new Jinja environment and setup a special module called9 `django.contrib.jinja` which exports a couple of functions useful for Jinja.1011 Quickstart12 ==========1314 To get started execute the following code at the bottom of your settings.py15 or in some general application file such as urls.py or a central module. The16 only thing that matters is that it's executed right *after* the settings17 were set up and *before* `django.contrib.jinja` is imported::1819 from jinja.contrib import djangosupport20 djangosupport.configure()2122 What this does is setting up a Jinja environment for this django instance23 with loaders for `TEMPLATE_DIRS` etc. It also converts a couple of default24 django filters such as `date` and `timesince` which are not available in25 Jinja per default. If you want to change the list you can provide others26 by passing a list with filter import names as `convert_filters` keyword27 argument.2829 All other keyword arguments are forwarded to the environment. If you want30 to provide a loader yourself pass it a loader keyword argument.3132 Rendering Templates33 ===================3435 To render a template you can use the functions `render_to_string` or36 `render_to_response` from the `django.contrib.jinja` module::3738 from django.contrib.jinja import render_to_response39 resp = render_to_response('Hello {{ username }}!', {40 'username': req.session['username']41 }, req)4243 `render_to_string` and `render_to_response` take at least the name of44 the template as argument, then the optional dict which will become the45 context. If you also provide a request object as third argument the46 context processors will be applied.4748 `render_to_response` also takes a forth parameter which can be the49 content type which defaults to `DEFAULT_CONTENT_TYPE`.5051 Converting Filters52 ==================5354 One of the useful objects provided by `django.contrib.jinja` is the55 `register` object which can be used to register filters, tests and56 global objects. You can also convert any filter django provides in57 a Jinja filter using `convert_django_filter`::5859 from django.contrib.jinja import register, convert_django_filter60 from django.template.defaultfilters import floatformat6162 register.filter(convert_django_filter(floatformat), 'floatformat')6364 Available methods on the `register` object:6566 ``object (obj[, name])``67 Register a new global as name or with the object's name.68 Returns the function object unchanged so that you can use69 it as decorator if no name is provided.7071 ``filter (func[, name])``72 Register a function as filter with the name provided or73 the object's name as filtername.74 Returns the function object unchanged so that you can use75 it as decorator if no name is provided.7677 ``test (func[, name])``78 Register a function as test with the name provided or the79 object's name as testname.80 Returns the function object unchanged so that you can use81 it as decorator if no name is provided.8283 ``context_inclusion (func, template[, name])``84 Register a function with a name provided or the func object's85 name in the global namespace that acts as subrender function.8687 func is called with the callers context as dict and the88 arguments and keywords argument of the inclusion function.89 The function should then process the context and return a90 new context or the same context object. Afterwards the91 template is rendered with this context.9293 Example::9495 def add_author(context, author=None):96 if author is not None:97 author = Author.objects.get(name=author)98 context['author'] = author99 return context100101 register.context_inclusion(add_author, 'author_details.html',102 'render_author_details')103104 You can use it in the template like this then::105106 {{ render_author_details('John Doe') }}107108 ``clean_inclusion (func, template[, name[, run_processors]]) ``109 Works like `context_inclusion` but doesn't use the calles110 context but an empty context. If `run_processors` is `True`111 it will lookup the context for a `request` object and pass112 it to the render function to apply context processors.113114 :copyright: 2007 by Armin Ronacher, Bryan McLemore.115 :license: BSD, see LICENSE for more details.116"""117try:118 __import__('django')119except ImportError:120 raise ImportError('installed django required for djangosupport')121else:122 from jinja.contrib._djangosupport import configure123124__all__ = ['configure']
deleted:jinja/translators/__init__.py-29 removed
1# -*- coding: utf-8 -*-2"""3 jinja.translators4 ~~~~~~~~~~~~~~~~~56 The submodules of this module provide translators for the jinja ast.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213class Translator(object):14 """15 Base class of all translators.16 """1718 def process(environment, tree, source=None):19 """20 Process the given ast with the rules defined in21 environment and return a translated version of it.22 The translated object can be anything. The python23 translator for example outputs Template instances,24 a javascript translator would probably output strings.2526 This is a static function.27 """28 pass29 process = staticmethod(process)
deleted:jinja/translators/python.py-1115 removed
1# -*- coding: utf-8 -*-2"""3 jinja.translators.python4 ~~~~~~~~~~~~~~~~~~~~~~~~56 This module translates a jinja ast into python code.78 This translator tries hard to keep Jinja sandboxed. All security9 relevant calls are wrapped by methods defined in the environment.10 This affects:1112 - method calls13 - attribute access14 - name resolution1516 It also adds debug symbols used by the traceback toolkit implemented17 in `jinja.utils`.1819 Implementation Details20 ======================2122 It might sound strange but the translator tries to keep the generated23 code readable as much as possible. This simplifies debugging the Jinja24 core a lot. The additional processing overhead is just relevant for25 the translation process, the additional comments and whitespace won't26 appear in the saved bytecode.2728 :copyright: 2007 by Armin Ronacher.29 :license: BSD, see LICENSE for more details.30"""31import re32import sys33from jinja import nodes34from jinja.nodes import get_nodes35from jinja.parser import Parser36from jinja.exceptions import TemplateSyntaxError37from jinja.translators import Translator38from jinja.datastructure import TemplateStream39from jinja.utils import set, capture_generator404142#: regular expression for the debug symbols43_debug_re = re.compile(r'^\s*\# DEBUG\(filename=(?P<filename>.*?), '44 r'lineno=(?P<lineno>\d+)\)$')4546# For Python versions without generator exit exceptions47try:48 GeneratorExit = GeneratorExit49except NameError:50 class GeneratorExit(Exception):51 pass5253# For Pythons without conditional expressions54try:55 exec '0 if 0 else 0'56 have_conditional_expr = True57except SyntaxError:58 have_conditional_expr = False596061class Template(object):62 """63 Represents a finished template.64 """6566 def __init__(self, environment, code):67 self.environment = environment68 self.code = code69 self.generate_func = None7071 def dump(self, stream=None):72 """Dump the template into python bytecode."""73 if stream is not None:74 from marshal import dump75 dump(self.code, stream)76 else:77 from marshal import dumps78 return dumps(self.code)7980 def load(environment, data):81 """Load the template from python bytecode."""82 if isinstance(data, basestring):83 from marshal import loads84 code = loads(data)85 else:86 from marshal import load87 code = load(data)88 return Template(environment, code)89 load = staticmethod(load)9091 def render(self, *args, **kwargs):92 """Render a template."""93 __traceback_hide__ = True94 ctx = self._prepare(*args, **kwargs)95 try:96 return capture_generator(self.generate_func(ctx))97 except:98 self._debug(ctx, *sys.exc_info())99100 def stream(self, *args, **kwargs):101 """Render a template as stream."""102 def proxy(ctx):103 try:104 for item in self.generate_func(ctx):105 yield item106 except GeneratorExit:107 return108 except:109 self._debug(ctx, *sys.exc_info())110 return TemplateStream(proxy(self._prepare(*args, **kwargs)))111112 def _prepare(self, *args, **kwargs):113 """Prepare the template execution."""114 # if there is no generation function we execute the code115 # in a new namespace and save the generation function and116 # debug information.117 env = self.environment118 if self.generate_func is None:119 ns = {'environment': env}120 exec self.code in ns121 self.generate_func = ns['generate']122 return env.context_class(env, *args, **kwargs)123124 def _debug(self, ctx, exc_type, exc_value, traceback):125 """Debugging Helper"""126 # just modify traceback if we have that feature enabled127 from traceback import print_exception128 print_exception(exc_type, exc_value, traceback)129130 if self.environment.friendly_traceback:131 # hook the debugger in132 from jinja.debugger import translate_exception133 exc_type, exc_value, traceback = translate_exception(134 self, ctx, exc_type, exc_value, traceback)135 print_exception(exc_type, exc_value, traceback)136137 raise exc_type, exc_value, traceback138139140class TranslationOperator(object):141 """142 A translation operator has a single string representing the operation143 """144 def __init__(self, operator, translator):145 self.operator = operator146 self.translator = translator147148class UnaryOperator(TranslationOperator):149 """150 A unary operator has one side to the operation.151 """152 def __call__(self, node):153 """154 Apply operator.155 """156 return '( %s %s)' % (157 self.operator,158 self.translator.handle_node(node.node),159 )160161class BinaryOperator(TranslationOperator):162 """163 A binary operator has two sides to the operation.164 """165 def __call__(self, node):166 """167 Apply operator.168 """169 return '(%s %s %s)' % (170 self.translator.handle_node(node.left),171 self.operator,172 self.translator.handle_node(node.right),173 )174175class PythonTranslator(Translator):176 """177 Pass this translator a ast tree to get valid python code.178 """179180 def __init__(self, environment, node, source):181 self.environment = environment182 self.loader = environment.loader.get_controlled_loader()183 self.node = node184 self.source = source185 self.closed = False186187 #: current level of indention188 self.indention = 0189 #: each {% cycle %} tag has a unique ID which increments190 #: automatically for each tag.191 self.last_cycle_id = 0192 #: set of used shortcuts jinja has to make local automatically193 self.used_shortcuts = set(['undefined_singleton'])194 #: set of used datastructures jinja has to import195 self.used_data_structures = set()196 #: set of used utils jinja has to import197 self.used_utils = set()198 #: flags for runtime error199 self.require_runtime_error = False200 #: do wee need a "set" object?201 self.need_set_import = False202 #: flag for regular expressions203 self.compiled_regular_expressions = {}204205 #: bind the nodes to the callback functions. There are206 #: some missing! A few are specified in the `unhandled`207 #: mapping in order to disallow their usage, some of them208 #: will not appear in the jinja parser output because209 #: they are filtered out.210 self.handlers = {211 # block nodes212 nodes.Template: self.handle_template,213 nodes.Text: self.handle_template_text,214 nodes.NodeList: self.handle_node_list,215 nodes.ForLoop: self.handle_for_loop,216 nodes.IfCondition: self.handle_if_condition,217 nodes.Cycle: self.handle_cycle,218 nodes.Print: self.handle_print,219 nodes.Macro: self.handle_macro,220 nodes.Call: self.handle_call,221 nodes.Set: self.handle_set,222 nodes.Filter: self.handle_filter,223 nodes.Block: self.handle_block,224 nodes.Include: self.handle_include,225 nodes.Trans: self.handle_trans,226227 # expression nodes228 nodes.NameExpression: self.handle_name,229 nodes.CompareExpression: self.handle_compare,230 nodes.TestExpression: self.handle_test,231 nodes.ConstantExpression: self.handle_const,232 nodes.RegexExpression: self.handle_regex,233 nodes.SubscriptExpression: self.handle_subscript,234 nodes.FilterExpression: self.handle_filter_expr,235 nodes.CallExpression: self.handle_call_expr,236 nodes.AddExpression: BinaryOperator('+', self),237 nodes.SubExpression: BinaryOperator('-', self),238 nodes.ConcatExpression: self.handle_concat,239 nodes.DivExpression: BinaryOperator('/', self),240 nodes.FloorDivExpression: BinaryOperator('//', self),241 nodes.MulExpression: BinaryOperator('*', self),242 nodes.ModExpression: BinaryOperator('%', self),243 nodes.PosExpression: UnaryOperator('+', self),244 nodes.NegExpression: UnaryOperator('-', self),245 nodes.PowExpression: BinaryOperator('**', self),246 nodes.DictExpression: self.handle_dict,247 nodes.SetExpression: self.handle_set_expr,248 nodes.ListExpression: self.handle_list,249 nodes.TupleExpression: self.handle_tuple,250 nodes.UndefinedExpression: self.handle_undefined,251 nodes.AndExpression: BinaryOperator(' and ', self),252 nodes.OrExpression: BinaryOperator(' or ', self),253 nodes.NotExpression: UnaryOperator(' not ', self),254 nodes.SliceExpression: self.handle_slice,255 nodes.ConditionalExpression: self.handle_conditional_expr256 }257258 # -- public methods259260 def process(environment, node, source=None):261 """262 The only public method. Creates a translator instance,263 translates the code and returns it in form of an264 `Template` instance.265 """266 translator = PythonTranslator(environment, node, source)267 filename = node.filename or '<template>'268 source = translator.translate()269 return Template(environment, compile(source, filename, 'exec'))270 process = staticmethod(process)271272 # -- private helper methods273274 def indent(self, text):275 """276 Indent the current text. This does only indent the277 first line.278 """279 return (' ' * (self.indention * 4)) + text280281 def to_tuple(self, args):282 """283 Return a tuple repr without nested repr.284 """285 return '(%s%s)' % (286 ', '.join(args),287 len(args) == 1 and ',' or ''288 )289290 def nodeinfo(self, node, force=False):291 """292 Return a comment that helds the node informations or None293 if there is no need to add a debug comment.294 """295 return '# DEBUG(filename=%s, lineno=%s)' % (296 node.filename or '',297 node.lineno298 )299300 def handle_node(self, node):301 """302 Handle one node. Resolves the correct callback functions defined303 in the callback mapping.304 """305 if self.closed:306 raise RuntimeError('translator is closed')307 if node.__class__ in self.handlers:308 return self.handlers[node.__class__](node)309 else:310 raise AssertionError('unhandled node %r' % node.__class__)311312 def close(self):313 """314 Clean up stuff.315 """316 self.closed = True317 self.handlers = self.node = self.environment = self.loader = None318319 def translate(self):320 """321 Translate the node defined in the constructor.322 """323 try:324 return self.handle_node(self.node)325 finally:326 self.close()327328 # -- jinja nodes329330 def handle_template(self, node):331 """332 Handle the overall template node. This node is the first node and333 ensures that we get the bootstrapping code. It also knows about334 inheritance information. It only occours as outer node, never in335 the tree itself.336 """337 self.indention = 1338339 # if there is a parent template we parse the parent template and340 # update the blocks there. Once this is done we drop the current341 # template in favor of the new one. Do that until we found the342 # root template.343 parent = None344 overwrites = {}345 blocks = {}346 requirements = []347 outer_filename = node.filename or '<template>'348349 # this set is required in order to not add blocks to the block350 # dict a second time if they were not overridden in one template351 # in the template chain.352 already_registered_block = set()353354 while node.extends is not None:355 # the direct child nodes in a template that are not blocks356 # are processed as template globals, thus executed *before*357 # the master layout template is loaded. This can be used358 # for further processing. The output of those nodes does359 # not appear in the final template.360 requirements += [child for child in node.body.get_child_nodes()361 if child.__class__ not in (nodes.Text,362 nodes.Block)]363364 # load the template we inherit from and add not known blocks.365 # this also marks the templates on the controlled loader but366 # are never removed. that's no problem because we don't allow367 # parents we extend from as includes and the controlled loader368 # is only used for this templated369 parent = self.loader.parse(node.extends,370 node.filename)371372 # look up all block nodes in the current template and373 # add them to the override dict.374 for n in get_nodes(nodes.Block, node):375 overwrites[n.name] = n376 # handle direct overrides377 for n in get_nodes(nodes.Block, parent):378 # an overwritten block for the parent template. handle that379 # override in the template and register it in the deferred380 # block dict.381 if n.name in overwrites and n not in already_registered_block:382 blocks.setdefault(n.name, []).append(n.clone())383 n.replace(overwrites[n.name])384 already_registered_block.add(n)385 # make the parent node the new node386 node = parent387388 # handle requirements code389 if requirements:390 requirement_lines = ['def bootstrap(context):']391 for n in requirements:392 requirement_lines.append(self.handle_node(n))393 requirement_lines.append(' if 0: yield None\n')394395 # handle body in order to get the used shortcuts396 body_code = self.handle_node(node.body)397398 # same for blocks in callables399 block_lines = []400 block_items = blocks.items()401 block_items.sort()402 dict_lines = []403 for name, items in block_items:404 tmp = []405 for idx, item in enumerate(items):406 # ensure that the indention is correct407 self.indention = 1408 func_name = 'block_%s_%s' % (name, idx)409 data = self.handle_block(item, idx + 1)410 # blocks with data411 if data:412 block_lines.extend([413 'def %s(context):' % func_name,414 self.indent(self.nodeinfo(item, True)),415 data,416 ' if 0: yield None\n'417 ])418 tmp.append('buffereater(%s)' % func_name)419 self.used_utils.add('buffereater')420 # blocks without data, can default to something421 # from utils422 else:423 tmp.append('empty_block')424 self.used_utils.add('empty_block')425 dict_lines.append(' %r: %s' % (426 str(name),427 self.to_tuple(tmp)428 ))429430 # bootstrapping code431 lines = ['# Essential imports', 'from __future__ import division']432 if self.used_utils:433 lines.append('from jinja.utils import %s' % \434 ', '.join(tuple(self.used_utils)))435 if self.require_runtime_error:436 lines.append('from jinja.exceptions import TemplateRuntimeError')437 if self.used_data_structures:438 lines.append('from jinja.datastructure import %s' % ', '.439 join(self.used_data_structures))440 if self.need_set_import:441 lines.append('from jinja.utils import set')442443 # compile regular expressions444 if self.compiled_regular_expressions:445 lines.append('import re')446 lines.append('\n# Compile used regular expressions')447 for regex, name in self.compiled_regular_expressions.iteritems():448 lines.append('%s = re.compile(%r)' % (name, regex))449450 lines.append(451 '\n# Aliases for some speedup\n'452 '%s\n\n'453 '# Marker for Jinja templates\n'454 '__jinja_template__ = True\n\n'455 '# Name for disabled debugging\n'456 '__name__ = %r\n\n'457 'def generate(context):\n'458 ' assert environment is context.environment' % (459 '\n'.join([460 '%s = environment.%s' % (item, item) for item in461 self.used_shortcuts462 ]),463 outer_filename464 )465 )466467 # the template body468 if requirements:469 lines.append(' for item in bootstrap(context): pass')470 lines.append(body_code)471 lines.append(' if 0: yield None\n')472473 # now write the bootstrapping (requirements) core if there is one474 if requirements:475 lines.append('# Bootstrapping code')476 lines.extend(requirement_lines)477478 # blocks must always be defined. even if it's empty. some479 # features depend on it480 if block_lines:481 lines.append('# Superable blocks')482 lines.extend(block_lines)483 lines.append('# Block mapping')484 if dict_lines:485 lines.append('blocks = {\n%s\n}\n' % ',\n'.join(dict_lines))486 else:487 lines.append('blocks = {}\n')488489 # now get the real source lines and map the debugging symbols490 debug_mapping = []491 file_mapping = {}492 last = None493 offset = -1494 sourcelines = ('\n'.join(lines)).splitlines()495 result = []496497 for idx, line in enumerate(sourcelines):498 m = _debug_re.search(line)499 if m is not None:500 d = m.groupdict()501 filename = d['filename'] or None502 if isinstance(filename, unicode):503 filename = filename.encode('utf-8')504 if filename in file_mapping:505 file_id = file_mapping[filename]506 else:507 file_id = file_mapping[filename] = 'F%d' % \508 len(file_mapping)509 this = (file_id, int(d['lineno']))510 # if it's the same as the line before we ignore it511 if this != last:512 debug_mapping.append('(%r, %s, %r)' % ((idx - offset,) + this))513 last = this514 # for each debug symbol the line number and so the offset515 # changes by one.516 offset += 1517 else:518 result.append(line)519520 # now print file mapping and debug info521 # the debug info:522 # debug_info binds template line numbers to generated523 # source lines. this information is always524 # present and part of the bytecode.525 # template_source only available if loaded from string to526 # get debug source code. Because this is527 # dumped too it's a bad idea to dump templates528 # loaded from a string.529 result.append('\n# Debug Information')530 file_mapping = file_mapping.items()531 file_mapping.sort(lambda a, b: cmp(a[1], b[1]))532 for filename, file_id in file_mapping:533 result.append('%s = %r' % (file_id, filename))534 result.append('debug_info = %s' % self.to_tuple(debug_mapping))535 result.append('template_source = %r' % self.source)536537 return '\n'.join(result)538539 def handle_template_text(self, node):540 """541 Handle data around nodes.542 """543 # special case: no variables544 if not node.variables:545 return self.indent(self.nodeinfo(node)) + '\n' + \546 self.indent('yield %r' % node.text.replace('%%', '%'))547548 # special case: one variable, no text549 self.used_shortcuts.add('finish_var')550 if len(node.variables) == 1 and node.text == '%s':551 return self.indent(self.nodeinfo(node)) + '\n' + \552 self.indent('yield finish_var(%s, context)' %553 self.handle_node(node.variables[0]))554555 # all other cases556 buf = []557 write = lambda x: buf.append(self.indent(x))558559 write(self.nodeinfo(node))560 write('yield %r %% (' % node.text)561 self.indention += 1562 for var in node.variables:563 write(self.nodeinfo(var))564 write('finish_var(%s, context)' % self.handle_node(var) + ',')565 self.indention -= 1566 write(')')567568 return '\n'.join(buf)569570 def handle_node_list(self, node):571 """572 In some situations we might have a node list. It's just573 a collection of multiple statements.574575 If the nodelist was empty it will return an empty string576 """577 body = '\n'.join([self.handle_node(n) for n in node])578 if body:579 return self.indent(self.nodeinfo(node)) + '\n' + body580 return ''581582 def handle_for_loop(self, node):583 """584 Handle a for loop. Pretty basic, just that we give the else585 clause a different behavior.586 """587 self.used_data_structures.add('LoopContext')588 buf = []589 write = lambda x: buf.append(self.indent(x))590 write(self.nodeinfo(node))591 write('context.push()')592593 # recursive loops594 if node.recursive:595 write('def loop(seq):')596 self.indention += 1597 write('for %s in context[\'loop\'].push(seq):' %598 self.handle_node(node.item),599 )600601 # simple loops602 else:603 write('context[\'loop\'] = loop = LoopContext(%s, '604 'context[\'loop\'], None)' % self.handle_node(node.seq))605 write('for %s in loop:' %606 self.handle_node(node.item)607 )608609 # handle real loop code610 self.indention += 1611 write(self.nodeinfo(node.body))612 if node.body:613 buf.append(self.handle_node(node.body))614 else:615 write('pass')616 self.indention -= 1617618 # else part of loop619 if node.else_:620 write('if not context[\'loop\'].iterated:')621 self.indention += 1622 write(self.nodeinfo(node.else_))623 buf.append(self.handle_node(node.else_) or self.indent('pass'))624 self.indention -= 1625626 # call recursive for loop!627 if node.recursive:628 write('context[\'loop\'].pop()')629 write('if 0: yield None')630 self.indention -= 1631 write('context[\'loop\'] = LoopContext(None, context[\'loop\'], '632 'buffereater(loop))')633 self.used_utils.add('buffereater')634 write('for item in loop(%s):' % self.handle_node(node.seq))635 self.indention += 1636 write('yield item')637 self.indention -= 1638639 write('context.pop()')640 return '\n'.join(buf)641642 def handle_if_condition(self, node):643 """644 Handle an if condition node.645 """646 buf = []647 write = lambda x: buf.append(self.indent(x))648 write(self.nodeinfo(node))649 for idx, (test, body) in enumerate(node.tests):650 write('%sif %s:' % (651 idx and 'el' or '',652 self.handle_node(test)653 ))654 self.indention += 1655 write(self.nodeinfo(body))656 buf.append(self.handle_node(body) or self.indent('pass'))657 self.indention -= 1658 if node.else_ is not None:659 write('else:')660 self.indention += 1661 write(self.nodeinfo(node.else_))662 buf.append(self.handle_node(node.else_) or self.indent('pass'))663 self.indention -= 1664 return '\n'.join(buf)665666 def handle_cycle(self, node):667 """668 Handle the cycle tag.669 """670 self.used_data_structures.add('CycleContext')671 name = '::cycle_%x' % self.last_cycle_id672 self.last_cycle_id += 1673 buf = []674 write = lambda x: buf.append(self.indent(x))675676 write('if %r not in context.current:' % name)677 self.indention += 1678 write(self.nodeinfo(node))679 if node.seq.__class__ in (nodes.TupleExpression,680 nodes.ListExpression):681 write('context.current[%r] = CycleContext(%s)' % (682 name,683 self.to_tuple([self.handle_node(n) for n in node.seq.items])684 ))685 hardcoded = True686 else:687 write('context.current[%r] = CycleContext()' % name)688 hardcoded = False689 self.indention -= 1690691 self.used_shortcuts.add('finish_var')692 if hardcoded:693 write('yield finish_var(context.current[%r].cycle(), '694 'context)' % name)695 else:696 write('yield finish_var(context.current[%r].cycle(%s), '697 'context)' % (698 name,699 self.handle_node(node.seq)700 ))701702 return '\n'.join(buf)703704 def handle_print(self, node):705 """706 Handle a print statement.707 """708 self.used_shortcuts.add('finish_var')709 return self.indent(self.nodeinfo(node)) + '\n' +\710 self.indent('yield finish_var(%s, context)' %711 self.handle_node(node.expr))712713 def handle_macro(self, node):714 """715 Handle macro declarations.716 """717 buf = []718 write = lambda x: buf.append(self.indent(x))719720 write('def macro(*args, **kw):')721 self.indention += 1722 write(self.nodeinfo(node))723724 # collect macro arguments725 arg_items = []726 caller_overridden = False727728 # if we have conditional expressions available in that python729 # build (for example cpython > 2.4) we can use them, they730 # will perform slightly better.731 if have_conditional_expr:732 arg_tmpl = '\'%(name)s\': args[%(pos)d] if argcount > %(pos)d ' \733 'else %(default)s'734 # otherwise go with the and/or tuple hack:735 else:736 arg_tmpl = '\'%(name)s\': (argcount > %(pos)d and '\737 '(args[%(pos)d],) or (%(default)s,))[0]'738739 if node.arguments:740 varargs_init = '\'varargs\': args[%d:]' % len(node.arguments)741 write('argcount = len(args)')742 for idx, (name, n) in enumerate(node.arguments):743 arg_items.append(arg_tmpl % {744 'name': name,745 'pos': idx,746 'default': n is None and 'undefined_singleton' or747 self.handle_node(n)748 })749 if name == 'caller':750 caller_overridden = True751 elif name == 'varargs':752 varargs_init = None753 else:754 varargs_init = '\'varargs\': args'755756 if caller_overridden:757 write('kw.pop(\'caller\', None)')758 else:759 arg_items.append('\'caller\': kw.pop(\'caller\', undefined_singleton)')760 if varargs_init:761 arg_items.append(varargs_init)762763 write('context.push({%s})' % ',\n '.join([764 idx and self.indent(item) or item for idx, item765 in enumerate(arg_items)766 ]))767768 # disallow any keyword arguments769 write('if kw:')770 self.indention += 1771 write('raise TemplateRuntimeError(\'%s got an unexpected keyword '772 'argument %%r\' %% iter(kw).next())' % node.name)773 self.require_runtime_error = True774 self.indention -= 1775776 write(self.nodeinfo(node.body))777 data = self.handle_node(node.body)778 if data:779 buf.append(data)780 write('context.pop()')781 write('if 0: yield None')782 self.indention -= 1783 buf.append(self.indent('context[%r] = buffereater(macro, True)' %784 node.name))785 self.used_utils.add('buffereater')786787 return '\n'.join(buf)788789 def handle_call(self, node):790 """791 Handle extended macro calls.792 """793 buf = []794 write = lambda x: buf.append(self.indent(x))795796 write('def call(**kwargs):')797 self.indention += 1798 write('context.push(kwargs)')799 data = self.handle_node(node.body)800 if data:801 buf.append(data)802 write('context.pop()')803 write('if 0: yield None')804 self.indention -= 1805 write('yield ' + self.handle_call_expr(node.expr,806 {'caller': 'buffereater(call)'}))807 self.used_utils.add('buffereater')808809 return '\n'.join(buf)810811 def handle_set(self, node):812 """813 Handle variable assignments.814 """815 if node.scope_local:816 tmpl = 'context[%r] = %s'817 else:818 tmpl = 'context.set_nonlocal(%r, %s)'819 return self.indent(self.nodeinfo(node)) + '\n' + \820 self.indent(tmpl % (821 node.name,822 self.handle_node(node.expr)823 ))824825 def handle_filter(self, node):826 """827 Handle filter sections.828 """829 buf = []830 write = lambda x: buf.append(self.indent(x))831 write('def filtered():')832 self.indention += 1833 write('context.push()')834 write(self.nodeinfo(node.body))835 data = self.handle_node(node.body)836 if data:837 buf.append(data)838 write('context.pop()')839 write('if 0: yield None')840 self.indention -= 1841 self.used_shortcuts.add('apply_filters')842 write('yield apply_filters(buffereater(filtered)(), context, %s)' %843 self.to_tuple(['(%r, %s)' % (844 name,845 self.to_tuple(map(self.handle_node, args))846 ) for name, args in node.filters])847 )848 self.used_utils.add('buffereater')849 return '\n'.join(buf)850851 def handle_block(self, node, level=0):852 """853 Handle blocks in the sourcecode. We only use them to854 call the current block implementation that is stored somewhere855 else.856 """857 rv = self.handle_node(node.body)858 if not rv:859 return ''860861 self.used_data_structures.add('SuperBlock')862 buf = []863 write = lambda x: buf.append(self.indent(x))864865 write(self.nodeinfo(node))866 write('context.push({\'super\': SuperBlock(%r, blocks, %r, context)})' % (867 str(node.name),868 level869 ))870 write(self.nodeinfo(node.body))871 buf.append(rv)872 write('context.pop()')873 return '\n'.join(buf)874875 def handle_include(self, node):876 """877 Include another template at the current position.878 """879 tmpl = self.loader.parse(node.template,880 node.filename)881 try:882 return self.handle_node(tmpl.body)883 finally:884 self.loader.mark_as_processed()885886 def handle_trans(self, node):887 """888 Handle translations.889 """890 if node.replacements:891 replacements = []892 for name, n in node.replacements.iteritems():893 replacements.append('%r: %s' % (894 name,895 self.handle_node(n)896 ))897 replacements = '{%s}' % ', '.join(replacements)898 else:899 replacements = 'None'900 return self.indent(self.nodeinfo(node)) + '\n' +\901 self.indent('yield context.translate_func(%r, %r, %r, %s)' % (902 node.singular,903 node.plural,904 node.indicator,905 replacements906 ))907908 # -- python nodes909910 def handle_name(self, node):911 """912 Handle name assignments and name retreivement.913 """914 if node.name == '_':915 return 'context.translate_func'916 return 'context[%r]' % node.name917918 def handle_compare(self, node):919 """920 Any sort of comparison921 """922 ops = {923 'eq': '==',924 'ne': '!=',925 'lt': '<',926 'lteq': '<=',927 'gt': '>',928 'gteq': '>=',929 'in': 'in',930 'not in': 'not in'931 }932 buf = []933 buf.append(self.handle_node(node.expr))934 for op, n in node.ops:935 buf.append(ops[op])936 buf.append(self.handle_node(n))937 return ' '.join(buf)938939 def handle_test(self, node):940 """941 Handle test calls.942 """943 self.used_shortcuts.add('perform_test')944 return 'perform_test(context, %r, %s, %s)' % (945 node.name,946 self.to_tuple([self.handle_node(n) for n in node.args]),947 self.handle_node(node.node)948 )949950 def handle_const(self, node):951 """952 Constant values in expressions.953 """954 return repr(node.value)955956 def handle_regex(self, node):957 """958 Regular expression literals.959 """960 if self.environment.disable_regexps:961 raise TemplateSyntaxError('regular expressions disabled.')962 if node.value in self.compiled_regular_expressions:963 return self.compiled_regular_expressions[node.value]964 name = 'regex_%d' % len(self.compiled_regular_expressions)965 self.compiled_regular_expressions[node.value] = name966 return name967968 def handle_subscript(self, node):969 """970 Handle variable based attribute access foo['bar'].971 """972 self.used_shortcuts.add('get_attribute')973 if node.arg.__class__ is nodes.SliceExpression:974 rv = self.handle_slice(node.arg, getslice_test=True)975 if rv is not None:976 return self.handle_node(node.node) + rv977 return 'get_attribute(%s, %s)' % (978 self.handle_node(node.node),979 self.handle_node(node.arg)980 )981982 def handle_tuple(self, node):983 """984 Tuple unpacking loops.985 """986 return self.to_tuple([self.handle_node(n) for n in node.items])987988 def handle_filter_expr(self, node):989 """990 We use the pipe operator for filtering.991 """992 self.used_shortcuts.add('apply_filters')993 return 'apply_filters(%s, context, %s)' % (994 self.handle_node(node.node),995 self.to_tuple(['(%r, %s)' % (996 name,997 self.to_tuple(map(self.handle_node, args))998 ) for name, args in node.filters])999 )10001001 def handle_call_expr(self, node, extra_kwargs=None):1002 """1003 Handle function calls.1004 """1005 args = []1006 kwargs = {}1007 dyn_args = dyn_kwargs = None1008 if node.dyn_args is not None:1009 dyn_args = self.handle_node(node.dyn_args)1010 if node.dyn_kwargs is not None:1011 dyn_kwargs = self.handle_node(node.dyn_kwargs)1012 for arg in node.args:1013 args.append(self.handle_node(arg))1014 for name, arg in node.kwargs:1015 kwargs[name] = self.handle_node(arg)1016 if extra_kwargs:1017 kwargs.update(extra_kwargs)1018 if not (args or kwargs or dyn_args or dyn_kwargs):1019 self.used_shortcuts.add('call_function_simple')1020 return 'call_function_simple(%s, context)' % \1021 self.handle_node(node.node)1022 self.used_shortcuts.add('call_function')1023 return 'call_function(%s, context, %s, {%s}, %s, %s)' % (1024 self.handle_node(node.node),1025 self.to_tuple(args),1026 ', '.join(['%r: %s' % i for i in kwargs.iteritems()]),1027 dyn_args,1028 dyn_kwargs1029 )10301031 def handle_concat(self, node):1032 """1033 Convert some objects to unicode and concatenate them.1034 """1035 self.used_shortcuts.add('to_unicode')1036 return "u''.join(%s)" % self.to_tuple([1037 'to_unicode(%s)' % self.handle_node(arg)1038 for arg in node.args1039 ])104010411042 def handle_dict(self, node):1043 """1044 Dict constructor syntax.1045 """1046 return '{%s}' % ', '.join([1047 '%s: %s' % (1048 self.handle_node(key),1049 self.handle_node(value)1050 ) for key, value in node.items1051 ])10521053 def handle_set_expr(self, node):1054 """1055 Set constructor syntax.1056 """1057 self.need_set_import = True1058 return 'set([%s])' % ', '.join([self.handle_node(n)1059 for n in node.items])10601061 def handle_list(self, node):1062 """1063 We don't know tuples, tuples are lists for jinja.1064 """1065 return '[%s]' % ', '.join([1066 self.handle_node(n) for n in node.items1067 ])10681069 def handle_undefined(self, node):1070 """1071 Return the current undefined literal.1072 """1073 return 'undefined_singleton'107410751076 def handle_slice(self, node, getslice_test=False):1077 """1078 Slice access. Because of backwards compatibilty to python's1079 `__getslice__` this function takes a second parameter that lets this1080 method return a regular slice bracket call. If a regular slice bracket1081 call that is compatible to __getslice__ is not possible the return1082 value will be `None` so that a regular `get_attribute` wrapping can1083 happen.1084 """1085 if node.start is None:1086 start = not getslice_test and 'None' or ''1087 else:1088 start = self.handle_node(node.start)1089 if node.stop is None:1090 stop = not getslice_test and 'None' or ''1091 else:1092 stop = self.handle_node(node.stop)1093 if node.step is None:1094 step = 'None'1095 else:1096 if getslice_test:1097 return1098 step = self.handle_node(node.step)1099 if getslice_test:1100 return '[%s:%s]' % (start, stop)1101 return 'slice(%s, %s, %s)' % (start, stop, step)11021103 def handle_conditional_expr(self, node):1104 """1105 Handle conditional expressions.1106 """1107 if have_conditional_expr:1108 tmpl = '%(expr1)s if %(test)s else %(expr2)s'1109 else:1110 tmpl = '(%(test)s and (%(expr1)s,) or (%(expr2)s,))[0]'1111 return tmpl % {1112 'test': self.handle_node(node.test),1113 'expr1': self.handle_node(node.expr1),1114 'expr2': self.handle_node(node.expr2)1115 }
deleted:jinja/__init__.py-76 removed
1# -*- coding: utf-8 -*-2"""3 jinja4 ~~~~~56 Jinja is a `sandboxed`_ template engine written in pure Python. It7 provides a `Django`_ like non-XML syntax and compiles templates into8 executable python code. It's basically a combination of Django templates9 and python code.1011 Nutshell12 --------1314 Here a small example of a Jinja template::1516 {% extends 'base.html' %}17 {% block title %}Memberlist{% endblock %}18 {% block content %}19 <ul>20 {% for user in users %}21 <li><a href="{{ user.url|e }}">{{ user.username|e }}</a></li>22 {% endfor %}23 </ul>24 {% endblock %}2526 Philosophy27 ----------2829 Application logic is for the controller but don't try to make the life30 for the template designer too hard by giving him too few functionality.3132 For more informations visit the new `jinja webpage`_ and `documentation`_.3334 Note35 ----3637 This is the Jinja 1.0 release which is completely incompatible with the38 old "pre 1.0" branch. The old branch will still receive security updates39 and bugfixes but the 1.0 branch will be the only version that receives40 support.4142 If you have an application that uses Jinja 0.9 and won't be updated in43 the near future the best idea is to ship a Jinja 0.9 checkout together44 with the application.4546 The `Jinja tip`_ is installable via `easy_install` with ``easy_install47 Jinja==dev``.4849 .. _sandboxed: http://en.wikipedia.org/wiki/Sandbox_(computer_security)50 .. _Django: http://www.djangoproject.com/51 .. _jinja webpage: http://jinja.pocoo.org/52 .. _documentation: http://jinja.pocoo.org/documentation/index.html53 .. _Jinja tip: http://dev.pocoo.org/hg/jinja-main/archive/tip.tar.gz#egg=Jinja-dev545556 :copyright: 2007 by Armin Ronacher.57 :license: BSD, see LICENSE for more details.58"""5960from jinja.environment import Environment61from jinja.datastructure import Markup62from jinja.plugin import jinja_plugin_factory as template_plugin_factory63from jinja.loaders import FileSystemLoader, PackageLoader, DictLoader, \64 ChoiceLoader, FunctionLoader, MemcachedFileSystemLoader65from jinja.utils import from_string666768__all__ = ['Environment', 'Markup', 'FileSystemLoader', 'PackageLoader',69 'DictLoader', 'ChoiceLoader', 'FunctionLoader',70 'MemcachedFileSystemLoader', 'from_string']7172__version__ = '1.3'73__author__ = 'Armin Ronacher'74__url__ = 'http://jinja.pocoo.org/'75__license__ = 'BSD'76__docformat__ = 'restructuredtext'
deleted:jinja/_debugger.c-65 removed
1/**2 * Jinja Extended Debugger3 * ~~~~~~~~~~~~~~~~~~~~~~~4 *5 * this module allows the jinja debugger to set the tb_next flag6 * on traceback objects. This is required to inject a traceback into7 * another one.8 *9 * For better windows support (not everybody has a visual studio 200310 * at home) it would be a good thing to have a ctypes implementation, but11 * because the struct is not exported there is currently no sane way.12 *13 * :copyright: 2007 by Armin Ronacher.14 * :license: BSD, see LICENSE for more details.15 */1617#include <Python.h>181920/**21 * set the tb_next attribute of a traceback object22 */23static PyObject *24tb_set_next(PyObject *self, PyObject *args)25{26 PyTracebackObject *tb, *old;27 PyObject *next;2829 if (!PyArg_ParseTuple(args, "O!O:tb_set_next", &PyTraceBack_Type, &tb, &next))30 return NULL;31 if (next == Py_None)32 next = NULL;33 else if (!PyTraceBack_Check(next)) {34 PyErr_SetString(PyExc_TypeError,35 "tb_set_next arg 2 must be traceback or None");36 return NULL;37 }38 else39 Py_INCREF(next);4041 old = tb->tb_next;42 tb->tb_next = (PyTracebackObject*)next;43 Py_XDECREF(old);4445 Py_INCREF(Py_None);46 return Py_None;47}484950static PyMethodDef module_methods[] = {51 {"tb_set_next", (PyCFunction)tb_set_next, METH_VARARGS,52 "Set the tb_next member of a traceback object."},53 {NULL, NULL, 0, NULL} /* Sentinel */54};5556#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */57#define PyMODINIT_FUNC void58#endif59PyMODINIT_FUNC60init_debugger(void)61{62 PyObject *module = Py_InitModule3("jinja._debugger", module_methods, "");63 if (!module)64 return;65}
deleted:jinja/_native.py-85 removed
1# -*- coding: utf-8 -*-2"""3 jinja._native4 ~~~~~~~~~~~~~56 This module implements the native base classes in case of not7 having a jinja with the _speedups module compiled.89 Note that if you change semantics here you have to edit the10 _speedups.c file to in order to support those changes for jinja11 setups with enabled speedup module.1213 :copyright: 2007 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15"""16from jinja.datastructure import Deferred17from jinja.utils import deque181920class BaseContext(object):2122 def __init__(self, undefined_singleton, globals, initial):23 self._undefined_singleton = undefined_singleton24 self.current = current = {}25 self._stack = deque([current, initial, globals])26 self.globals = globals27 self.initial = initial2829 self._push = self._stack.appendleft30 self._pop = self._stack.popleft3132 def stack(self):33 return list(self._stack)[::-1]34 stack = property(stack)3536 def pop(self):37 """Pop the last layer from the stack and return it."""38 rv = self._pop()39 self.current = self._stack[0]40 return rv4142 def push(self, data=None):43 """44 Push one layer to the stack and return it. Layer must be45 a dict or omitted.46 """47 data = data or {}48 self._push(data)49 self.current = self._stack[0]50 return data5152 def __getitem__(self, name):53 """54 Resolve one item. Restrict the access to internal variables55 such as ``'::cycle1'``. Resolve deferreds.56 """57 if not name.startswith('::'):58 for d in self._stack:59 if name in d:60 rv = d[name]61 if rv.__class__ is Deferred:62 rv = rv(self, name)63 # never touch the globals!64 if d is self.globals:65 self.initial[name] = rv66 else:67 d[name] = rv68 return rv69 return self._undefined_singleton7071 def __setitem__(self, name, value):72 """Set a variable in the outermost layer."""73 self.current[name] = value7475 def __delitem__(self, name):76 """Delete a variable in the outermost layer."""77 if name in self.current:78 del self.current[name]7980 def __contains__(self, name):81 """ Check if the context contains a given variable."""82 for layer in self._stack:83 if name in layer:84 return True85 return False
deleted:jinja/_speedups.c-499 removed
1/**2 * jinja._speedups3 * ~~~~~~~~~~~~~~~4 *5 * This module implements the BaseContext, a c implementation of the6 * Context baseclass. If this extension is not compiled the datastructure7 * module implements a class in python.8 *9 * Note that if you change semantics here you have to edit the _native.py10 * to in order to support those changes for jinja setups without the11 * speedup module too.12 *13 * :copyright: 2007 by Armin Ronacher.14 * :license: BSD, see LICENSE for more details.15 */1617#include <Python.h>18#include <structmember.h>1920/* Set by init_constants to real values */21static PyObject *Deferred;2223/**24 * Internal struct used by BaseContext to store the25 * stacked namespaces.26 */27struct StackLayer {28 PyObject *dict; /* current value, a dict */29 struct StackLayer *prev; /* lower struct layer or NULL */30};3132/**33 * BaseContext python class.34 */35typedef struct {36 PyObject_HEAD37 struct StackLayer *globals; /* the dict for the globals */38 struct StackLayer *initial; /* initial values */39 struct StackLayer *current; /* current values */40 long stacksize; /* current size of the stack */41 PyObject *undefined_singleton; /* the singleton returned on missing values */42} BaseContext;4344/**45 * Called by init_speedups in order to retrieve references46 * to some exceptions and classes defined in jinja python modules47 */48static int49init_constants(void)50{51 PyObject *datastructure = PyImport_ImportModule("jinja.datastructure");52 if (!datastructure)53 return 0;54 Deferred = PyObject_GetAttrString(datastructure, "Deferred");55 Py_DECREF(datastructure);56 return 1;57}5859/**60 * GC Helper61 */62static int63BaseContext_clear(BaseContext *self)64{65 struct StackLayer *current = self->current, *tmp;66 while (current) {67 tmp = current;68 Py_XDECREF(current->dict);69 current->dict = NULL;70 current = tmp->prev;71 PyMem_Free(tmp);72 }73 self->current = NULL;74 return 0;75}7677/**78 * Deallocator for BaseContext.79 *80 * Frees the memory for the stack layers before freeing the object.81 */82static void83BaseContext_dealloc(BaseContext *self)84{85 BaseContext_clear(self);86 self->ob_type->tp_free((PyObject*)self);87}8889/**90 * GC Helper91 */92static int93BaseContext_traverse(BaseContext *self, visitproc visit, void *args)94{95 int vret;96 struct StackLayer *layer = self->current;9798 while (layer) {99 vret = visit(layer->dict, args);100 if (vret != 0)101 return vret;102 layer = layer->prev;103 }104105 return 0;106}107108/**109 * Initializes the BaseContext.110 *111 * Like the native python class it takes a reference to the undefined112 * singleton which will be used for undefined values.113 * The other two arguments are the global namespace and the initial114 * namespace which usually contains the values passed to the render115 * function of the template. Both must be dicts.116 */117static int118BaseContext_init(BaseContext *self, PyObject *args, PyObject *kwds)119{120 PyObject *undefined = NULL, *globals = NULL, *initial = NULL;121122 if (!PyArg_ParseTuple(args, "OOO", &undefined, &globals, &initial))123 return -1;124 if (!PyDict_Check(globals) || !PyDict_Check(initial)) {125 PyErr_SetString(PyExc_TypeError, "stack layers must be dicts.");126 return -1;127 }128129 self->current = PyMem_Malloc(sizeof(struct StackLayer));130 self->current->prev = NULL;131 self->current->dict = PyDict_New();132 if (!self->current->dict)133 return -1;134135 self->initial = PyMem_Malloc(sizeof(struct StackLayer));136 self->initial->prev = NULL;137 self->initial->dict = initial;138 Py_INCREF(initial);139 self->current->prev = self->initial;140141 self->globals = PyMem_Malloc(sizeof(struct StackLayer));142 self->globals->prev = NULL;143 self->globals->dict = globals;144 Py_INCREF(globals);145 self->initial->prev = self->globals;146147 self->undefined_singleton = undefined;148 Py_INCREF(undefined);149150 self->stacksize = 3;151 return 0;152}153154/**155 * Pop the highest layer from the stack and return it156 */157static PyObject*158BaseContext_pop(BaseContext *self)159{160 PyObject *result;161 struct StackLayer *tmp = self->current;162163 if (self->stacksize <= 3) {164 PyErr_SetString(PyExc_IndexError, "stack too small.");165 return NULL;166 }167 result = self->current->dict;168 assert(result);169 self->current = tmp->prev;170 PyMem_Free(tmp);171 self->stacksize--;172 /* Took the reference to result from the struct. */173 return result;174}175176/**177 * Push a new layer to the stack and return it. If no parameter178 * is provided an empty dict is created. Otherwise the dict passed179 * to it is used as new layer.180 */181static PyObject*182BaseContext_push(BaseContext *self, PyObject *args)183{184 PyObject *value = NULL;185 struct StackLayer *new;186187 if (!PyArg_ParseTuple(args, "|O:push", &value))188 return NULL;189 if (!value) {190 value = PyDict_New();191 if (!value)192 return NULL;193 }194 else if (!PyDict_Check(value)) {195 PyErr_SetString(PyExc_TypeError, "dict required.");196 return NULL;197 }198 else199 Py_INCREF(value);200 new = PyMem_Malloc(sizeof(struct StackLayer));201 if (!new) {202 Py_DECREF(value);203 return NULL;204 }205 new->dict = value;206 new->prev = self->current;207 self->current = new;208 self->stacksize++;209 Py_INCREF(value);210 return value;211}212213/**214 * Getter that creates a list representation of the internal215 * stack. Used for compatibility with the native python implementation.216 */217static PyObject*218BaseContext_getstack(BaseContext *self, void *closure)219{220 int idx = 0;221 struct StackLayer *current = self->current;222 PyObject *result = PyList_New(self->stacksize);223 if (!result)224 return NULL;225 while (current) {226 Py_INCREF(current->dict);227 PyList_SET_ITEM(result, idx++, current->dict);228 current = current->prev;229 }230 PyList_Reverse(result);231 return result;232}233234/**235 * Getter that returns a reference to the current layer in the context.236 */237static PyObject*238BaseContext_getcurrent(BaseContext *self, void *closure)239{240 Py_INCREF(self->current->dict);241 return self->current->dict;242}243244/**245 * Getter that returns a reference to the initial layer in the context.246 */247static PyObject*248BaseContext_getinitial(BaseContext *self, void *closure)249{250 Py_INCREF(self->initial->dict);251 return self->initial->dict;252}253254/**255 * Getter that returns a reference to the global layer in the context.256 */257static PyObject*258BaseContext_getglobals(BaseContext *self, void *closure)259{260 Py_INCREF(self->globals->dict);261 return self->globals->dict;262}263264/**265 * Implements the context lookup.266 *267 * This works exactly like the native implementation but a lot268 * faster. It disallows access to internal names (names that start269 * with "::") and resolves Deferred values.270 */271static PyObject*272BaseContext_getitem(BaseContext *self, PyObject *item)273{274 PyObject *result;275 char *name = NULL;276 int isdeferred;277 struct StackLayer *current = self->current;278 279 /* allow unicode keys as long as they are ascii keys */280 if (PyUnicode_CheckExact(item)) {281 item = PyUnicode_AsASCIIString(item);282 if (!item)283 goto missing;284 }285 else if (!PyString_Check(item))286 goto missing;287288 /* disallow access to internal jinja values */289 name = PyString_AS_STRING(item);290 if (name[0] == ':' && name[1] == ':')291 goto missing;292293 while (current) {294 /* GetItemString just builds a new string from "name" again... */295 result = PyDict_GetItem(current->dict, item);296 if (!result) {297 current = current->prev;298 continue;299 }300 isdeferred = PyObject_IsInstance(result, Deferred);301 if (isdeferred == -1)302 return NULL;303 else if (isdeferred) {304 PyObject *namespace;305 PyObject *resolved = PyObject_CallFunctionObjArgs(306 result, self, item, NULL);307 if (!resolved)308 return NULL;309310 /* never touch the globals */311 if (current == self->globals)312 namespace = self->initial->dict;313 else314 namespace = current->dict;315 if (PyDict_SetItem(namespace, item, resolved) < 0)316 return NULL;317 Py_INCREF(resolved);318 return resolved;319 }320 Py_INCREF(result);321 return result;322 }323324missing:325 Py_INCREF(self->undefined_singleton);326 return self->undefined_singleton;327}328329/**330 * Check if the context contains a given value.331 */332static int333BaseContext_contains(BaseContext *self, PyObject *item)334{335 char *name;336 struct StackLayer *current = self->current;337338 /* allow unicode objects as keys as long as they are ASCII */339 if (PyUnicode_CheckExact(item)) {340 item = PyUnicode_AsASCIIString(item);341 if (!item)342 return 0;343 }344 else if (!PyString_Check(item))345 return 0;346347 name = PyString_AS_STRING(item);348 if (name[0] == ':' && name[1] == ':')349 return 0;350351 while (current) {352 /* XXX: for 2.4 and newer, use PyDict_Contains */353 if (!PyMapping_HasKey(current->dict, item)) {354 current = current->prev;355 continue;356 }357 return 1;358 }359360 return 0;361}362363/**364 * Set an value in the highest layer or delete one.365 */366static int367BaseContext_setitem(BaseContext *self, PyObject *item, PyObject *value)368{369 /* allow unicode objects as keys as long as they are ASCII */370 if (PyUnicode_CheckExact(item)) {371 item = PyUnicode_AsASCIIString(item);372 if (!item) {373 PyErr_Clear();374 goto error;375 }376 }377 else if (!PyString_Check(item))378 goto error;379 if (!value)380 return PyDict_DelItem(self->current->dict, item);381 return PyDict_SetItem(self->current->dict, item, value);382383error:384 PyErr_SetString(PyExc_TypeError, "expected string argument");385 return -1;386}387388389static PyGetSetDef BaseContext_getsetters[] = {390 {"stack", (getter)BaseContext_getstack, NULL,391 "a read only copy of the internal stack", NULL},392 {"current", (getter)BaseContext_getcurrent, NULL,393 "reference to the current layer on the stack", NULL},394 {"initial", (getter)BaseContext_getinitial, NULL,395 "reference to the initial layer on the stack", NULL},396 {"globals", (getter)BaseContext_getglobals, NULL,397 "reference to the global layer on the stack", NULL},398 {NULL} /* Sentinel */399};400401static PyMethodDef BaseContext_methods[] = {402 {"pop", (PyCFunction)BaseContext_pop, METH_NOARGS,403 "ctx.pop() -> dict\n\n"404 "Pop the last layer from the stack and return it."},405 {"push", (PyCFunction)BaseContext_push, METH_VARARGS,406 "ctx.push([layer]) -> layer\n\n"407 "Push one layer to the stack. Layer must be a dict "408 "or omitted."},409 {NULL} /* Sentinel */410};411412static PySequenceMethods BaseContext_as_sequence = {413 0, /* sq_length */414 0, /* sq_concat */415 0, /* sq_repeat */416 0, /* sq_item */417 0, /* sq_slice */418 0, /* sq_ass_item */419 0, /* sq_ass_slice */420 (objobjproc)BaseContext_contains,/* sq_contains */421 0, /* sq_inplace_concat */422 0 /* sq_inplace_repeat */423};424425static PyMappingMethods BaseContext_as_mapping = {426 NULL,427 (binaryfunc)BaseContext_getitem,428 (objobjargproc)BaseContext_setitem429};430431static PyTypeObject BaseContextType = {432 PyObject_HEAD_INIT(NULL)433 0, /* ob_size */434 "jinja._speedups.BaseContext", /* tp_name */435 sizeof(BaseContext), /* tp_basicsize */436 0, /* tp_itemsize */437 (destructor)BaseContext_dealloc,/* tp_dealloc */438 0, /* tp_print */439 0, /* tp_getattr */440 0, /* tp_setattr */441 0, /* tp_compare */442 0, /* tp_repr */443 0, /* tp_as_number */444 &BaseContext_as_sequence, /* tp_as_sequence */445 &BaseContext_as_mapping, /* tp_as_mapping */446 0, /* tp_hash */447 0, /* tp_call */448 0, /* tp_str */449 0, /* tp_getattro */450 0, /* tp_setattro */451 0, /* tp_as_buffer */452 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,453 /*tp_flags*/454 "", /* tp_doc */455 (traverseproc)BaseContext_traverse, /* tp_traverse */456 (inquiry)BaseContext_clear, /* tp_clear */457 0, /* tp_richcompare */458 0, /* tp_weaklistoffset */459 0, /* tp_iter */460 0, /* tp_iternext */461 BaseContext_methods, /* tp_methods */462 0, /* tp_members */463 BaseContext_getsetters, /* tp_getset */464 0, /* tp_base */465 0, /* tp_dict */466 0, /* tp_descr_get */467 0, /* tp_descr_set */468 0, /* tp_dictoffset */469 (initproc)BaseContext_init, /* tp_init */470 0, /* tp_alloc */471 0 /* tp_new */472};473474static PyMethodDef module_methods[] = {475 {NULL, NULL, 0, NULL} /* Sentinel */476};477478#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */479#define PyMODINIT_FUNC void480#endif481PyMODINIT_FUNC482init_speedups(void)483{484 PyObject *module;485486 BaseContextType.tp_new = (newfunc)PyType_GenericNew;487 if (PyType_Ready(&BaseContextType) < 0)488 return;489490 if (!init_constants())491 return;492493 module = Py_InitModule3("_speedups", module_methods, "");494 if (!module)495 return;496497 Py_INCREF(&BaseContextType);498 PyModule_AddObject(module, "BaseContext", (PyObject*)&BaseContextType);499}
deleted:jinja/constants.py-32 removed
1# -*- coding: utf-8 -*-2"""3 jinja.constants4 ~~~~~~~~~~~~~~~56 Various constants.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213#: list of lorem ipsum words used by the lipsum() helper function14LOREM_IPSUM_WORDS = u'''\15a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at16auctor augue bibendum blandit class commodo condimentum congue consectetuer17consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus18diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend19elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames20faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac21hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum22justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem23luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie24mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non25nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque26penatibus per pharetra phasellus placerat platea porta porttitor posuere27potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus28ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit29sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor30tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices31ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus32viverra volutpat vulputate'''
deleted:jinja/datastructure.py-708 removed
1# -*- coding: utf-8 -*-2"""3 jinja.datastructure4 ~~~~~~~~~~~~~~~~~~~56 Module that helds several data types used in the template engine.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja.exceptions import TemplateSyntaxError, TemplateRuntimeError1213_missing = object()141516def contextcallable(f):17 """18 Mark a function context callable.19 """20 f.jinja_context_callable = True21 return f222324def unsafe(f):25 """26 Mark function as unsafe.27 """28 f.jinja_unsafe_call = True29 return f303132def make_undefined(implementation):33 """34 Creates an undefined singleton based on a given implementation.35 It performs some tests that make sure the undefined type implements36 everything it should.37 """38 self = object.__new__(implementation)39 self.__reduce__()40 return self414243class AbstractUndefinedType(object):44 """45 Base class for any undefined type.46 """47 __slots__ = ()4849 def __init__(self):50 raise TypeError('cannot create %r instances' %51 self.__class__.__name__)5253 def __setattr__(self, name, value):54 raise AttributeError('%r object has no attribute %r' % (55 self.__class__.__name__,56 name57 ))5859 def __eq__(self, other):60 return self is other6162 def __ne__(self, other):63 return self is not other6465 def __copy__(self):66 return self67 __deepcopy__ = __copy__6869 def __repr__(self):70 return 'Undefined'7172 def __reduce__(self):73 raise TypeError('undefined objects have to provide a __reduce__')747576class SilentUndefinedType(AbstractUndefinedType):77 """78 An object that does not exist.79 """80 __slots__ = ()8182 def __add__(self, other):83 """Any operator returns the operand."""84 return other85 __sub__ = __mul__ = __div__ = __rsub__ = __rmul__ = __div__ = __mod__ =\86 __radd__ = __rmod__ = __add__8788 def __getitem__(self, arg):89 """Getting any item returns `Undefined`"""90 return self9192 def __iter__(self):93 """Iterating over `Undefined` returns an empty iterator."""94 if False:95 yield None9697 def __getattr__(self, arg):98 """Getting any attribute returns `Undefined`"""99 return self100101 def __nonzero__(self):102 """`Undefined` is considered boolean `False`"""103 return False104105 def __len__(self):106 """`Undefined` is an empty sequence"""107 return 0108109 def __str__(self):110 """The string representation is empty."""111 return ''112113 def __unicode__(self):114 """The unicode representation is empty."""115 return u''116117 def __int__(self):118 """Converting `Undefined` to an integer ends up in ``0``"""119 return 0120121 def __float__(self):122 """Converting `Undefined` to an float ends up in ``0.0``"""123 return 0.0124125 def __call__(self, *args, **kwargs):126 """Calling `Undefined` returns `Undefined`"""127 return self128129 def __reduce__(self):130 """Helper for pickle."""131 return 'SilentUndefined'132133134class ComplainingUndefinedType(AbstractUndefinedType):135 """136 An object that does not exist.137 """138 __slots__ = ()139140 def __len__(self):141 """Getting the length raises error."""142 raise TemplateRuntimeError('Operated on undefined object')143144 def __iter__(self):145 """Iterating over `Undefined` raises an error."""146 raise TemplateRuntimeError('Iterated over undefined object')147148 def __nonzero__(self):149 """`Undefined` is considered boolean `False`"""150 return False151152 def __str__(self):153 """The string representation raises an error."""154 raise TemplateRuntimeError('Undefined object rendered')155156 def __unicode__(self):157 """The unicode representation raises an error."""158 self.__str__()159160 def __call__(self, *args, **kwargs):161 """Calling `Undefined` returns `Undefined`"""162 raise TemplateRuntimeError('Undefined object called')163164 def __reduce__(self):165 """Helper for pickle."""166 return 'ComplainingUndefined'167168169#: the singleton instances for the undefined objects170SilentUndefined = make_undefined(SilentUndefinedType)171ComplainingUndefined = make_undefined(ComplainingUndefinedType)172173#: jinja 1.0 compatibility174Undefined = SilentUndefined175UndefinedType = SilentUndefinedType176177178class FakeTranslator(object):179 """180 Default null translator.181 """182183 def gettext(self, s):184 """185 Translate a singular string.186 """187 return s188189 def ngettext(self, s, p, n):190 """191 Translate a plural string.192 """193 if n == 1:194 return s195 return p196197198class Deferred(object):199 """200 Object marking an deferred value. Deferred objects are201 objects that are called first access in the context.202 """203204 def __init__(self, factory):205 self.factory = factory206207 def __call__(self, context, name):208 return self.factory(context.environment, context, name)209210211class Markup(unicode):212 """213 Compatibility for Pylons and probably some other frameworks.214215 It's only used in Jinja environments with `auto_escape` set216 to true.217 """218219 def __html__(self):220 return unicode(self)221222223class TemplateData(Markup):224 """225 Subclass of unicode to mark objects that are coming from the226 template. The autoescape filter can use that.227 """228229230# import these here because those modules import Deferred and Undefined231# from this module.232try:233 # try to use the c implementation of the base context if available234 from jinja._speedups import BaseContext235except ImportError:236 # if there is no c implementation we go with a native python one237 from jinja._native import BaseContext238239240class Context(BaseContext):241 """242 Dict like object containing the variables for the template.243 """244245 def __init__(self, *args, **kwargs):246 environment = args[0]247 if not kwargs and len(args) == 2 and isinstance(args[1], dict):248 base = args[1]249 else:250 base = dict(*args[1:], **kwargs)251 super(Context, self).__init__(environment.undefined_singleton,252 environment.globals, base)253 self._translate_func = None254 self.cache = {}255 self.environment = environment256257 def to_dict(self):258 """259 Convert the context into a dict. This skips the globals.260 """261 result = {}262 for layer in self.stack[1:]:263 for key, value in layer.iteritems():264 if key.startswith('::'):265 continue266 result[key] = value267 return result268269 def set_nonlocal(self, name, value):270 """271 Set a value in an outer scope.272 """273 for layer in self.stack[:0:-1]:274 if name in layer:275 layer[name] = value276 return277 self.initial[name] = value278279 def translate_func(self):280 """281 The translation function for this context. It takes282 4 parameters. The singular string, the optional plural one,283 The name of the variable in the replacements dict and the284 replacements dict. This is only used by the i18n system285 internally the simplified version (just one argument) is286 available in the template for the user too.287 """288 if self._translate_func is not None:289 return self._translate_func290 translator = self.environment.get_translator(self)291 gettext = translator.gettext292 ngettext = translator.ngettext293 def translate(s, p=None, n=None, r=None):294 if p is None:295 s = gettext(s)296 else:297 s = ngettext(s, p, r[n])298 # apply replacement substitution only if replacements299 # are given. This is the case for {% trans %}...{% endtrans %}300 # but for the "_()" syntax and a trans tag without a body.301 if r is not None:302 return s % r303 return s304 translate.__doc__ = Context.translate_func.__doc__305 self._translate_func = translate306 return translate307 translate_func = property(translate_func, doc=translate_func.__doc__)308309 def __repr__(self):310 """311 String representation of the context.312 """313 return 'Context(%r)' % self.to_dict()314315 def __pretty__(self, p, cycle):316 if cycle:317 return p.text('Context({...})')318 p.begin_group(9, 'Context({')319 for idx, (key, value) in enumerate(self.to_dict().iteritems()):320 if idx:321 p.text(',')322 p.breakable()323 p.pretty(key)324 p.text(': ')325 p.pretty(value)326 p.end_group(9, '})')327328329class LoopContext(object):330 """331 Simple class that provides special loop variables.332 Used by `Environment.iterate`.333 """334335 jinja_allowed_attributes = ['index', 'index0', 'length', 'parent',336 'even', 'odd', 'revindex0', 'revindex',337 'first', 'last']338339 def __init__(self, seq, parent, loop_function):340 self.loop_function = loop_function341 self.parent = parent342 self._stack = []343 if loop_function is None:344 self.push(seq)345346 def push(self, seq):347 """348 Push a sequence to the loop stack. This is used by the349 recursive for loop.350 """351 # iteration over None is catched, but we don't catch iteration352 # over undefined because that behavior is handled in the353 # undefined singleton354 if seq is None:355 seq = ()356 length = 0357 else:358 try:359 length = len(seq)360 except (AttributeError, TypeError):361 seq = list(seq)362 length = len(seq)363 self._stack.append({364 'index': -1,365 'seq': seq,366 'length': length367 })368 return self369370 def pop(self):371 """Remove the last layer from the loop stack."""372 return self._stack.pop()373374 iterated = property(lambda s: s._stack[-1]['index'] > -1)375 index0 = property(lambda s: s._stack[-1]['index'])376 index = property(lambda s: s._stack[-1]['index'] + 1)377 revindex0 = property(lambda s: s._stack[-1]['length'] -378 s._stack[-1]['index'] - 1)379 revindex = property(lambda s: s._stack[-1]['length'] -380 s._stack[-1]['index'])381 length = property(lambda s: s._stack[-1]['length'])382 even = property(lambda s: s._stack[-1]['index'] % 2 == 1)383 odd = property(lambda s: s._stack[-1]['index'] % 2 == 0)384 first = property(lambda s: s._stack[-1]['index'] == 0)385 last = property(lambda s: s._stack[-1]['index'] ==386 s._stack[-1]['length'] - 1)387388 def __iter__(self):389 s = self._stack[-1]390 for idx, item in enumerate(s['seq']):391 s['index'] = idx392 yield item393394 def __len__(self):395 return self._stack[-1]['length']396397 def __call__(self, seq):398 if self.loop_function is not None:399 return self.loop_function(seq)400 raise TemplateRuntimeError('In order to make loops callable you have '401 'to define them with the "recursive" '402 'modifier.')403404 def __repr__(self):405 if self._stack:406 return '<LoopContext %d/%d%s>' % (407 self.index,408 self.length,409 self.loop_function is not None and ' recursive' or ''410 )411 return '<LoopContext (empty)>'412413414class CycleContext(object):415 """416 Helper class used for cycling.417 """418419 def __init__(self, seq=None):420 self.pos = -1421 # bind the correct helper function based on the constructor signature422 if seq is not None:423 self.seq = seq424 self.length = len(seq)425 self.cycle = self.cycle_static426 else:427 self.cycle = self.cycle_dynamic428429 def cycle_static(self):430 """Helper function for static cycling."""431 self.pos = (self.pos + 1) % self.length432 return self.seq[self.pos]433434 def cycle_dynamic(self, seq):435 """Helper function for dynamic cycling."""436 self.pos = pos = (self.pos + 1) % len(seq)437 return seq[pos]438439440class SuperBlock(object):441 """442 Helper class for ``{{ super() }}``.443 """444 jinja_allowed_attributes = ['name']445446 def __init__(self, name, blocks, level, context):447 self.name = name448 self.context = context449 if name in blocks:450 self.stack = blocks[name]451 self.level = level452 else:453 self.stack = None454455 def __call__(self, offset=1):456 if self.stack is not None:457 level = self.level + (offset - 1)458 if level < len(self.stack):459 return self.stack[level](self.context)460 raise TemplateRuntimeError('no super block for %r' % self.name)461462 def __repr__(self):463 return '<SuperBlock %r>' % self.name464465466class StateTest(object):467 """468 Wrapper class for basic lambdas in order to simplify469 debugging in the parser. It also provides static helper470 functions that replace some lambda expressions471 """472473 def __init__(self, func, msg):474 self.func = func475 self.msg = msg476477 def __call__(self, token):478 return self.func(token)479480 def expect_token(*types, **kw):481 """Scans until one of the given tokens is found."""482 msg = kw.pop('msg', None)483 if kw:484 raise TypeError('unexpected keyword argument %r' % iter(kw).next())485 if len(types) == 1:486 if msg is None:487 msg = "expected '%s'" % types[0]488 return StateTest(lambda t: t.type == types[0], msg)489 if msg is None:490 msg = 'expected one of %s' % ', '.join(["'%s'" % type491 for type in types])492 return StateTest(lambda t: t.type in types, msg)493 expect_token = staticmethod(expect_token)494495496class Token(object):497 """498 Token class.499 """500 __slots__ = ('lineno', 'type', 'value')501502 def __init__(self, lineno, type, value):503 self.lineno = lineno504 self.type = intern(str(type))505 self.value = value506507 def __str__(self):508 from jinja.lexer import keywords, reverse_operators509 if self.type in keywords:510 return self.type511 elif self.type in reverse_operators:512 return reverse_operators[self.type]513 return self.value514515 def __repr__(self):516 return 'Token(%r, %r, %r)' % (517 self.lineno,518 self.type,519 self.value520 )521522523class TokenStreamIterator(object):524 """525 The iterator for tokenstreams. Iterate over the stream526 until the eof token is reached.527 """528529 def __init__(self, stream):530 self._stream = stream531532 def __iter__(self):533 return self534535 def next(self):536 token = self._stream.current537 if token.type == 'eof':538 self._stream.close()539 raise StopIteration()540 self._stream.next()541 return token542543544class TokenStream(object):545 """546 A token stream wraps a generator and supports pushing tokens back.547 It also provides some functions to expect tokens and similar stuff.548549 Important note: Do never push more than one token back to the550 stream. Although the stream object won't stop you551 from doing so, the behavior is undefined. Multiple552 pushed tokens are only used internally!553 """554555 def __init__(self, generator, filename):556 self._next = generator.next557 self._pushed = []558 self.current = Token(1, 'initial', '')559 self.filename = filename560 self.next()561562 def __iter__(self):563 return TokenStreamIterator(self)564565 def bound(self):566 """Return True if the token stream is bound to a parser."""567 return self.parser is not None568 bound = property(bound, doc=bound.__doc__)569570 def lineno(self):571 """The current line number."""572 return self.current.lineno573 lineno = property(lineno, doc=lineno.__doc__)574575 def __nonzero__(self):576 """Are we at the end of the tokenstream?"""577 return bool(self._pushed) or self.current.type != 'eof'578579 eos = property(lambda x: not x.__nonzero__(), doc=__nonzero__.__doc__)580581 def look(self):582 """See what's the next token."""583 if self._pushed:584 return self._pushed[-1]585 old_token = self.current586 self.next()587 new_token = self.current588 self.current = old_token589 self.push(new_token)590 return new_token591592 def push(self, token):593 """Push a token back to the stream."""594 self._pushed.append(token)595596 def skip(self, n):597 """Got n tokens ahead."""598 for x in xrange(n):599 self.next()600601 def shift(self, token):602 """603 Push one token into the stream.604 """605 old_current = self.current606 self.next()607 self.push(self.current)608 self.push(old_current)609 self.push(token)610 self.next()611612 def next(self):613 """Go one token ahead."""614 if self._pushed:615 self.current = self._pushed.pop()616 elif self.current.type != 'eof':617 try:618 self.current = self._next()619 except StopIteration:620 self.close()621622 def read_whitespace(self):623 """Read all the whitespace, up to the next tag."""624 lineno = self.current.lineno625 buf = []626 while self.current.type == 'data' and not \627 self.current.value.strip():628 buf.append(self.current.value)629 self.next()630 if buf:631 return Token(lineno, 'data', u''.join(buf))632633 def close(self):634 """Close the stream."""635 self.current = Token(self.current.lineno, 'eof', '')636 self._next = None637638 def expect(self, token_type, token_value=_missing):639 """Expect a given token type and return it"""640 if self.current.type != token_type:641 raise TemplateSyntaxError("expected token %r, got %r" %642 (token_type, self.current.type),643 self.current.lineno,644 self.filename)645 elif token_value is not _missing and \646 self.current.value != token_value:647 raise TemplateSyntaxError("expected %r, got %r" %648 (token_value, self.current.value),649 self.current.lineno,650 self.filename)651 try:652 return self.current653 finally:654 self.next()655656657class TemplateStream(object):658 """659 Wraps a genererator for outputing template streams.660 """661662 def __init__(self, gen):663 self._gen = gen664 self._next = gen.next665 self.buffered = False666667 def disable_buffering(self):668 """669 Disable the output buffering.670 """671 self._next = self._gen.next672 self.buffered = False673674 def enable_buffering(self, size=5):675 """676 Enable buffering. Buffer `size` items before677 yielding them.678 """679 if size <= 1:680 raise ValueError('buffer size too small')681 self.buffered = True682683 def buffering_next():684 buf = []685 c_size = 0686 push = buf.append687 next = self._gen.next688689 try:690 while True:691 item = next()692 if item:693 push(item)694 c_size += 1695 if c_size >= size:696 raise StopIteration()697 except StopIteration:698 if not c_size:699 raise700 return u''.join(buf)701702 self._next = buffering_next703704 def __iter__(self):705 return self706707 def next(self):708 return self._next()
deleted:jinja/debugger.py-213 removed
1# -*- coding: utf-8 -*-2"""3 jinja.debugger4 ~~~~~~~~~~~~~~56 This module implements helper function Jinja uses to give the users a7 possibility to develop Jinja templates like they would debug python code.8 It seamlessly integreates into the python traceback system, in fact it9 just modifies the trackback stack so that the line numbers are correct10 and the frame information are bound to the context and not the frame of11 the template evaluation loop.1213 To achive this it raises the exception it cought before in an isolated14 namespace at a given line. The locals namespace is set to the current15 template context.1617 The traceback generated by raising that exception is then either returned18 or linked with the former traceback if the `jinja._debugger` module is19 available. Because it's not possible to modify traceback objects from the20 python space this module is needed for this process.2122 If it's not available it just ignores the other frames. Because this can23 lead to actually harder to debug code there is a setting on the jinja24 environment to disable the debugging system.2526 The isolated namespace which is used to raise the exception also contains27 a `__loader__` name that helds a reference to a PEP 302 compatible loader.28 Because there are currently some traceback systems (such as the paste29 evalexception debugger) that do not provide the frame globals when30 retrieving the source from the linecache module, Jinja injects the source31 to the linecache module itself and changes the filename to a URL style32 "virtual filename" so that Jinja doesn't acidentally override other files33 in the linecache.3435 :copyright: 2007 by Armin Ronacher.36 :license: BSD, see LICENSE for more details.37"""3839import sys40from random import randrange4142# if we have extended debugger support we should really use it43try:44 from jinja._debugger import *45 has_extended_debugger = True46except ImportError:47 has_extended_debugger = False4849# we need the RUNTIME_EXCEPTION_OFFSET to skip the not used frames50from jinja.utils import reversed, RUNTIME_EXCEPTION_OFFSET515253def fake_template_exception(exc_type, exc_value, tb, filename, lineno,54 source, context_or_env, tb_back=None):55 """56 Raise an exception "in a template". Return a traceback57 object. This is used for runtime debugging, not compile time.58 """59 # some traceback systems allow to skip frames60 __traceback_hide__ = True6162 # create the namespace which will be the local namespace63 # of the new frame then. Some debuggers show local variables64 # so we better inject the context and not the evaluation loop context.65 from jinja.datastructure import Context66 if isinstance(context_or_env, Context):67 env = context_or_env.environment68 namespace = context_or_env.to_dict()69 else:70 env = context_or_env71 namespace = {}7273 # no unicode for filenames74 if isinstance(filename, unicode):75 filename = filename.encode('utf-8')7677 # generate an jinja unique filename used so that linecache78 # gets data that doesn't interfere with other modules79 if filename is None:80 vfilename = 'jinja://~%d' % randrange(0, 10000)81 filename = '<string>'82 else:83 vfilename = 'jinja://%s' % filename8485 # now create the used loaded and update the linecache86 loader = TracebackLoader(env, source, filename)87 loader.update_linecache(vfilename)88 globals = {89 '__name__': vfilename,90 '__file__': vfilename,91 '__loader__': loader92 }9394 # use the simple debugger to reraise the exception in the95 # line where the error originally occoured96 globals['__exception_to_raise__'] = (exc_type, exc_value)97 offset = '\n' * (lineno - 1)98 code = compile(offset + 'raise __exception_to_raise__[0], '99 '__exception_to_raise__[1]',100 vfilename or '<template>', 'exec')101 try:102 exec code in globals, namespace103 except:104 exc_info = sys.exc_info()105106 # if we have an extended debugger we set the tb_next flag so that107 # we don't loose the higher stack items.108 if has_extended_debugger:109 if tb_back is not None:110 tb_set_next(tb_back, exc_info[2])111 if tb is not None:112 tb_set_next(exc_info[2].tb_next, tb.tb_next)113114 # otherwise just return the exc_info from the simple debugger115 return exc_info116117118def translate_exception(template, context, exc_type, exc_value, tb):119 """120 Translate an exception and return the new traceback.121 """122 # depending on the python version we have to skip some frames to123 # step to get the frame of the current template. The frames before124 # are the toolchain used to render that thing.125 for x in xrange(RUNTIME_EXCEPTION_OFFSET):126 tb = tb.tb_next127128 result_tb = prev_tb = None129 initial_tb = tb130131 # translate all the jinja frames in this traceback132 while tb is not None:133 if tb.tb_frame.f_globals.get('__jinja_template__'):134 debug_info = tb.tb_frame.f_globals['debug_info']135136 # the next thing we do is matching the current error line against the137 # debugging table to get the correct source line. If we can't find the138 # filename and line number we return the traceback object unaltered.139 error_line = tb.tb_lineno140 for code_line, tmpl_filename, tmpl_line in reversed(debug_info):141 if code_line <= error_line:142 source = tb.tb_frame.f_globals['template_source']143 tb = fake_template_exception(exc_type, exc_value, tb,144 tmpl_filename, tmpl_line,145 source, context, prev_tb)[-1]146 break147 if result_tb is None:148 result_tb = tb149 prev_tb = tb150 tb = tb.tb_next151152 # under some conditions we cannot translate any frame. in that153 # situation just return the original traceback.154 return (exc_type, exc_value, result_tb or intial_tb)155156157def raise_syntax_error(exception, env, source=None):158 """159 This method raises an exception that includes more debugging160 informations so that debugging works better. Unlike161 `translate_exception` this method raises the exception with162 the traceback.163 """164 exc_info = fake_template_exception(exception, None, None,165 exception.filename,166 exception.lineno, source, env)167 raise exc_info[0], exc_info[1], exc_info[2]168169170class TracebackLoader(object):171 """172 Fake importer that just returns the source of a template. It's just used173 by Jinja interally and you shouldn't use it on your own.174 """175176 def __init__(self, environment, source, filename):177 self.loader = environment.loader178 self.source = source179 self.filename = filename180181 def update_linecache(self, virtual_filename):182 """183 Hacky way to let traceback systems know about the184 Jinja template sourcecode. Very hackish indeed.185 """186 # check for linecache, not every implementation of python187 # might have such an module (this check is pretty senseless188 # because we depend on cpython anway)189 try:190 from linecache import cache191 except ImportError:192 return193 data = self.get_source(None)194 cache[virtual_filename] = (195 len(data),196 None,197 data.splitlines(True),198 virtual_filename199 )200201 def get_source(self, impname):202 """Return the source as bytestring."""203 source = ''204 if self.source is not None:205 source = self.source206 elif self.loader is not None:207 try:208 source = self.loader.get_source(self.filename)209 except TemplateNotFound:210 pass211 if isinstance(source, unicode):212 source = source.encode('utf-8')213 return source
deleted:jinja/defaults.py-16 removed
1# -*- coding: utf-8 -*-2"""3 jinja.defaults4 ~~~~~~~~~~~~~~56 Jinja default filters and tags.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja.filters import FILTERS as DEFAULT_FILTERS12from jinja.tests import TESTS as DEFAULT_TESTS13from jinja.utils import NAMESPACE as DEFAULT_NAMESPACE141516__all__ = ['DEFAULT_FILTERS', 'DEFAULT_TESTS', 'DEFAULT_NAMESPACE']
deleted:jinja/environment.py-404 removed
1# -*- coding: utf-8 -*-2"""3 jinja.environment4 ~~~~~~~~~~~~~~~~~56 Provides a class that holds runtime and parsing time options.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja.lexer import Lexer12from jinja.parser import Parser13from jinja.loaders import LoaderWrapper14from jinja.datastructure import SilentUndefined, Markup, Context, FakeTranslator15from jinja.translators.python import PythonTranslator 16from jinja.utils import collect_translations, get_attribute17from jinja.exceptions import FilterNotFound, TestNotFound, \18 SecurityException, TemplateSyntaxError19from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE202122__all__ = ['Environment']232425#: minor speedup26_getattr = getattr272829class Environment(object):30 """31 The Jinja environment.3233 The core component of Jinja is the `Environment`. It contains34 important shared variables like configuration, filters, tests,35 globals and others.36 """3738 def __init__(self,39 block_start_string='{%',40 block_end_string='%}',41 variable_start_string='{{',42 variable_end_string='}}',43 comment_start_string='{#',44 comment_end_string='#}',45 trim_blocks=False,46 auto_escape=False,47 default_filters=None,48 template_charset='utf-8',49 charset='utf-8',50 namespace=None,51 loader=None,52 filters=None,53 tests=None,54 context_class=Context,55 undefined_singleton=SilentUndefined,56 disable_regexps=False,57 friendly_traceback=True,58 translator_factory=None,59 template_translator=PythonTranslator):60 """61 Here the possible initialization parameters:6263 ========================= ============================================64 `block_start_string` * the string marking the begin of a block.65 this defaults to ``'{%'``.66 `block_end_string` * the string marking the end of a block.67 defaults to ``'%}'``.68 `variable_start_string` * the string marking the begin of a print69 statement. defaults to ``'{{'``.70 `comment_start_string` * the string marking the begin of a71 comment. defaults to ``'{#'``.72 `comment_end_string` * the string marking the end of a comment.73 defaults to ``'#}'``.74 `trim_blocks` * If this is set to ``True`` the first newline75 after a block is removed (block, not76 variable tag!). Defaults to ``False``.77 `auto_escape` If this is set to ``True`` Jinja will78 automatically escape all variables using xml79 escaping methods. If you don't want to80 escape a string you have to wrap it in a81 ``Markup`` object from the82 ``jinja.datastructure`` module. If83 `auto_escape` is ``True`` there will be also84 a ``Markup`` object in the template85 namespace to define partial html fragments.86 Note that we do not recommend this feature.87 `default_filters` list of tuples in the form (``filter_name``,88 ``arguments``) where ``filter_name`` is the89 name of a registered filter and90 ``arguments`` a tuple with the filter91 arguments. The filters specified here will92 always be applied when printing data to the93 template. *new in Jinja 1.1*94 `template_charset` The charset of the templates. Defaults95 to ``'utf-8'``.96 `charset` Charset of all string input data. Defaults97 to ``'utf-8'``.98 `namespace` Global namespace for all templates.99 `loader` Specify a template loader.100 `filters` dict of filters or the default filters if101 not defined.102 `tests` dict of tests of the default tests if not103 defined.104 `context_class` the context class this template should use.105 See the `Context` documentation for more106 details.107 `undefined_singleton` The singleton value that is used for missing108 variables. *new in Jinja 1.1*109 `disable_regexps` Disable support for regular expresssions.110 `friendly_traceback` Set this to `False` to disable the developer111 friendly traceback rewriting. Whenever an112 runtime or syntax error occours jinja will113 try to make a developer friendly traceback114 that shows the error in the template line.115 This however can be annoying when debugging116 broken functions that are called from the117 template. *new in Jinja 1.1*118 `translator_factory` A callback function that is called with119 the context as first argument to get the120 translator for the current instance.121 *new in Jinja 1.2*122 `template_translator` An class that defines a static method called123 process which can be used to process the 124 template's AST into a compiled python module.125 *new in Jinja 1.2*126 ========================= ============================================127128 All of these variables except those marked with a star (*) are129 modifiable after environment initialization.130 """131132 # lexer / parser information133 self.block_start_string = block_start_string134 self.block_end_string = block_end_string135 self.variable_start_string = variable_start_string136 self.variable_end_string = variable_end_string137 self.comment_start_string = comment_start_string138 self.comment_end_string = comment_end_string139 self.trim_blocks = trim_blocks140141 # other stuff142 self.template_charset = template_charset143 self.charset = charset144 self.loader = loader145 if filters is None:146 filters = DEFAULT_FILTERS.copy()147 self.filters = filters148 if tests is None:149 tests = DEFAULT_TESTS.copy()150 self.tests = tests151 self.default_filters = default_filters or []152 self.context_class = context_class153 self.undefined_singleton = undefined_singleton154 self.disable_regexps = disable_regexps155 self.friendly_traceback = friendly_traceback156157 # global namespace158 if namespace is None:159 namespace = DEFAULT_NAMESPACE.copy()160 self.globals = namespace161162 # jinja 1.0 compatibility163 if auto_escape:164 self.default_filters.append(('escape', (True,)))165 self.globals['Markup'] = Markup166167 # and here the translator factory168 self.translator_factory = translator_factory169170 # and here the AST translator171 self.template_translator = template_translator172173 # create lexer174 self.lexer = Lexer(self)175176 def loader(self, value):177 """178 Get or set the template loader.179 """180 self._loader = LoaderWrapper(self, value)181 loader = property(lambda s: s._loader, loader, doc=loader.__doc__)182183 def parse(self, source, filename=None):184 """185 Parse the sourcecode and return the abstract syntax tree. This tree186 of nodes is used by the `translators`_ to convert the template into187 executable source- or bytecode.188189 .. _translators: translators.txt190 """191 parser = Parser(self, source, filename)192 return parser.parse()193194 def lex(self, source, filename=None):195 """196 Lex the given sourcecode and return a generator that yields tokens.197 The stream returned is not usable for Jinja but can be used if198 Jinja templates should be processed by other tools (for example199 syntax highlighting etc)200201 The tuples are returned in the form ``(lineno, token, value)``.202 """203 return self.lexer.tokeniter(source, filename)204205 def from_string(self, source):206 """207 Load and parse a template source and translate it into eval-able208 Python code. This code is wrapped within a `Template` class that209 allows you to render it.210 """211 from jinja.translators.python import PythonTranslator212 try:213 rv = PythonTranslator.process(self, Parser(self, source).parse(),214 source)215 except TemplateSyntaxError, e:216 # on syntax errors rewrite the traceback if wanted217 if not self.friendly_traceback:218 raise219 from jinja.debugger import raise_syntax_error220 if __debug__:221 __traceback_hide__ = True222 raise_syntax_error(e, self, source)223 else:224 return rv225226 def get_template(self, filename):227 """228 Load a template from a loader. If the template does not exist, you229 will get a `TemplateNotFound` exception.230 """231 return self._loader.load(filename, translator=self.template_translator)232233 def to_unicode(self, value):234 """235 Convert a value to unicode with the rules defined on the environment.236 """237 # undefined and None expand to ""238 if value in (None, self.undefined_singleton):239 return u''240 # things that are already unicode can pass. As long as nobody241 # does ugly things with the class it works for jinja too242 elif isinstance(value, unicode):243 return value244 # otherwise try to use __unicode__ or decode __str__245 try:246 return unicode(value)247 except UnicodeError:248 return str(value).decode(self.charset, 'ignore')249250 def get_translator(self, context):251 """252 Return the translator for i18n.253254 A translator is an object that provides the two functions255 ``gettext(string)`` and ``ngettext(singular, plural, n)``. Note256 that both of them have to return unicode!257 """258 if self.translator_factory is not None:259 return self.translator_factory(context)260 return FakeTranslator()261262 def get_translations(self, name):263 """264 Load template `name` and return all translatable strings (note that265 that it really just returns the strings form this template, not from266 the parent or any included templates!)267 """268 return collect_translations(self.loader.parse(name))269270 def get_translations_for_string(self, string):271 """272 Like `get_translations`, but the translations are loaded from a273 normal string that represents the template.274 """275 return collect_translations(self.parse(string))276277 def apply_filters(self, value, context, filters):278 """279 Apply a list of filters on the variable.280 """281 # some traceback systems allow to skip frames. but allow282 # disabling that via -O to not make things slow283 if __debug__:284 __traceback_hide__ = True285286 cache = context.cache287 for key in filters:288 if key in cache:289 func = cache[key]290 else:291 filtername, args = key292 if filtername not in self.filters:293 raise FilterNotFound(filtername)294 cache[key] = func = self.filters[filtername](*args)295 value = func(self, context, value)296 return value297298 def perform_test(self, context, testname, args, value):299 """300 Perform a test on a variable.301 """302 # some traceback systems allow to skip frames. but allow303 # disabling that via -O to not make things slow304 if __debug__:305 __traceback_hide__ = True306307 key = (testname, args)308 if key in context.cache:309 func = context.cache[key]310 else:311 if testname not in self.tests:312 raise TestNotFound(testname)313 context.cache[key] = func = self.tests[testname](*args)314 return not not func(self, context, value)315316 def get_attribute(self, obj, name):317 """318 Get one attribute from an object.319 """320 # some traceback systems allow to skip frames. but allow321 # disabling that via -O to not make things slow322 if __debug__:323 __traceback_hide__ = True324325 try:326 return obj[name]327 except (TypeError, KeyError, IndexError, AttributeError):328 try:329 return get_attribute(obj, name)330 except (AttributeError, SecurityException):331 pass332 if obj is self.undefined_singleton:333 return _getattr(obj, name)334 return self.undefined_singleton335336 def get_attributes(self, obj, attributes):337 """338 Get some attributes from an object. If attributes is an339 empty sequence the object is returned as it.340 """341 get = self.get_attribute342 for name in attributes:343 obj = get(obj, name)344 return obj345346 def call_function(self, f, context, args, kwargs, dyn_args, dyn_kwargs):347 """348 Function call helper. Called for all functions that are passed349 any arguments.350 """351 # some traceback systems allow to skip frames. but allow352 # disabling that via -O to not make things slow353 if __debug__:354 __traceback_hide__ = True355356 if dyn_args is not None:357 args += tuple(dyn_args)358 if dyn_kwargs is not None:359 kwargs.update(dyn_kwargs)360 if _getattr(f, 'jinja_unsafe_call', False) or \361 _getattr(f, 'alters_data', False):362 return self.undefined_singleton363 if _getattr(f, 'jinja_context_callable', False):364 args = (self, context) + args365 return f(*args, **kwargs)366367 def call_function_simple(self, f, context):368 """369 Function call without arguments. Because of the smaller signature and370 fewer logic here we have a bit of redundant code.371 """372 # some traceback systems allow to skip frames. but allow373 # disabling that via -O to not make things slow374 if __debug__:375 __traceback_hide__ = True376377 if _getattr(f, 'jinja_unsafe_call', False) or \378 _getattr(f, 'alters_data', False):379 return self.undefined_singleton380 if _getattr(f, 'jinja_context_callable', False):381 return f(self, context)382 return f()383384 def finish_var(self, value, ctx):385 """386 As long as no write_var function is passed to the template387 evaluator the source generated by the python translator will388 call this function for all variables.389 """390 # some traceback systems allow to skip frames. but allow391 # disabling that via -O to not make things slow392 if __debug__:393 __traceback_hide__ = True394395 if value is None:396 return u''397 elif value is self.undefined_singleton:398 return unicode(value)399 elif _getattr(value, 'jinja_no_finalization', False):400 return value401 val = self.to_unicode(value)402 if self.default_filters:403 val = self.apply_filters(val, ctx, self.default_filters)404 return val
deleted:jinja/exceptions.py-91 removed
1# -*- coding: utf-8 -*-2"""3 jinja.exceptions4 ~~~~~~~~~~~~~~~~56 Jinja exceptions.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213class TemplateError(RuntimeError):14 pass151617class SecurityException(TemplateError):18 """19 Raise if the template designer tried to do something dangerous.20 """212223class FilterNotFound(KeyError, TemplateError):24 """25 Raised if a filter does not exist.26 """2728 def __init__(self, message):29 KeyError.__init__(self, message)303132class FilterArgumentError(TypeError, TemplateError):33 """34 An argument passed to the filter was invalid.35 """3637 def __init__(self, message):38 TypeError.__init__(self, message)394041class TestNotFound(KeyError, TemplateError):42 """43 Raised if a test does not exist.44 """4546 def __init__(self, message):47 KeyError.__init__(self, message)484950class TestArgumentError(TypeError, TemplateError):51 """52 An argument passed to a test function was invalid.53 """5455 def __init__(self, message):56 TypeError.__init__(self, message)575859class TemplateNotFound(IOError, LookupError, TemplateError):60 """61 Raised if a template does not exist.62 """6364 def __init__(self, name):65 IOError.__init__(self, name)66 self.name = name676869class TemplateSyntaxError(SyntaxError, TemplateError):70 """71 Raised to tell the user that there is a problem with the template.72 """7374 def __init__(self, message, lineno, filename):75 SyntaxError.__init__(self, message)76 self.lineno = lineno77 self.filename = filename787980class TemplateRuntimeError(TemplateError):81 """82 Raised by the template engine if a tag encountered an error when83 rendering.84 """858687class TemplateIncludeError(TemplateError):88 """89 Raised by the `ControlledLoader` if recursive includes where90 detected.91 """
deleted:jinja/filters.py-989 removed
1# -*- coding: utf-8 -*-2"""3 jinja.filters4 ~~~~~~~~~~~~~56 Bundled jinja filters.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12from random import choice13try:14 from operator import itemgetter15except ImportError:16 itemgetter = lambda a: lambda b: b[a]17from urllib import urlencode, quote18from jinja.utils import urlize, escape, reversed, sorted, groupby, \19 get_attribute, pformat20from jinja.datastructure import TemplateData21from jinja.exceptions import FilterArgumentError, SecurityException222324_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')252627def stringfilter(f):28 """29 Decorator for filters that just work on unicode objects.30 """31 def decorator(*args):32 def wrapped(env, context, value):33 nargs = list(args)34 for idx, var in enumerate(nargs):35 if isinstance(var, str):36 nargs[idx] = env.to_unicode(var)37 return f(env.to_unicode(value), *nargs)38 return wrapped39 try:40 decorator.__doc__ = f.__doc__41 decorator.__name__ = f.__name__42 except:43 pass44 return decorator454647def simplefilter(f):48 """49 Decorator for simplifying filters. Filter arguments are passed50 to the decorated function without environment and context. The51 source value is the first argument. (like stringfilter but52 without unicode conversion)53 """54 def decorator(*args):55 def wrapped(env, context, value):56 return f(value, *args)57 return wrapped58 try:59 decorator.__doc__ = f.__doc__60 decorator.__name__ = f.__name__61 except:62 pass63 return decorator646566def do_replace(s, old, new, count=None):67 """68 Return a copy of the value with all occurrences of a substring69 replaced with a new one. The first argument is the substring70 that should be replaced, the second is the replacement string.71 If the optional third argument ``count`` is given, only the first72 ``count`` occurrences are replaced:7374 .. sourcecode:: jinja7576 {{ "Hello World"|replace("Hello", "Goodbye") }}77 -> Goodbye World7879 {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}80 -> d'oh, d'oh, aaargh81 """82 if not isinstance(old, basestring) or \83 not isinstance(new, basestring):84 raise FilterArgumentError('the replace filter requires '85 'string replacement arguments')86 if count is None:87 return s.replace(old, new)88 if not isinstance(count, (int, long)):89 raise FilterArgumentError('the count parameter of the '90 'replace filter requires '91 'an integer')92 return s.replace(old, new, count)93do_replace = stringfilter(do_replace)949596def do_upper(s):97 """98 Convert a value to uppercase.99 """100 return s.upper()101do_upper = stringfilter(do_upper)102103104def do_lower(s):105 """106 Convert a value to lowercase.107 """108 return s.lower()109do_lower = stringfilter(do_lower)110111112def do_escape(attribute=False):113 """114 XML escape ``&``, ``<``, and ``>`` in a string of data. If the115 optional parameter is `true` this filter will also convert116 ``"`` to ``&quot;``. This filter is just used if the environment117 was configured with disabled `auto_escape`.118119 This method will have no effect it the value is already escaped.120 """121 #: because filters are cached we can make a local alias to122 #: speed things up a bit123 e = escape124 def wrapped(env, context, s):125 if isinstance(s, TemplateData):126 return s127 elif hasattr(s, '__html__'):128 return s.__html__()129 #: small speedup, do not convert to unicode if we already130 #: have an unicode object.131 if s.__class__ is not unicode:132 s = env.to_unicode(s)133 return e(s, attribute)134 return wrapped135136137def do_xmlattr(autospace=False):138 """139 Create an SGML/XML attribute string based on the items in a dict.140 All values that are neither `none` nor `undefined` are automatically141 escaped:142143 .. sourcecode:: html+jinja144145 <ul{{ {'class': 'my_list', 'missing': None,146 'id': 'list-%d'|format(variable)}|xmlattr }}>147 ...148 </ul>149150 Results in something like this:151152 .. sourcecode:: html153154 <ul class="my_list" id="list-42">155 ...156 </ul>157158 As you can see it automatically prepends a space in front of the item159 if the filter returned something. You can disable this by passing160 `false` as only argument to the filter.161162 *New in Jinja 1.1*163 """164 e = escape165 def wrapped(env, context, d):166 if not hasattr(d, 'iteritems'):167 raise TypeError('a dict is required')168 result = []169 for key, value in d.iteritems():170 if value not in (None, env.undefined_singleton):171 result.append(u'%s="%s"' % (172 e(env.to_unicode(key)),173 e(env.to_unicode(value), True)174 ))175 rv = u' '.join(result)176 if autospace:177 rv = ' ' + rv178 return rv179 return wrapped180181182def do_capitalize(s):183 """184 Capitalize a value. The first character will be uppercase, all others185 lowercase.186 """187 return s.capitalize()188do_capitalize = stringfilter(do_capitalize)189190191def do_title(s):192 """193 Return a titlecased version of the value. I.e. words will start with194 uppercase letters, all remaining characters are lowercase.195 """196 return s.title()197do_title = stringfilter(do_title)198199200def do_dictsort(case_sensitive=False, by='key'):201 """202 Sort a dict and yield (key, value) pairs. Because python dicts are203 unsorted you may want to use this function to order them by either204 key or value:205206 .. sourcecode:: jinja207208 {% for item in mydict|dictsort %}209 sort the dict by key, case insensitive210211 {% for item in mydict|dicsort(true) %}212 sort the dict by key, case sensitive213214 {% for item in mydict|dictsort(false, 'value') %}215 sort the dict by key, case insensitive, sorted216 normally and ordered by value.217 """218 if by == 'key':219 pos = 0220 elif by == 'value':221 pos = 1222 else:223 raise FilterArgumentError('You can only sort by either '224 '"key" or "value"')225 def sort_func(value, env):226 if isinstance(value, basestring):227 value = env.to_unicode(value)228 if not case_sensitive:229 value = value.lower()230 return value231232 def wrapped(env, context, value):233 items = value.items()234 items.sort(lambda a, b: cmp(sort_func(a[pos], env),235 sort_func(b[pos], env)))236 return items237 return wrapped238239240def do_default(default_value=u'', boolean=False):241 """242 If the value is undefined it will return the passed default value,243 otherwise the value of the variable:244245 .. sourcecode:: jinja246247 {{ my_variable|default('my_variable is not defined') }}248249 This will output the value of ``my_variable`` if the variable was250 defined, otherwise ``'my_variable is not defined'``. If you want251 to use default with variables that evaluate to false you have to252 set the second parameter to `true`:253254 .. sourcecode:: jinja255256 {{ ''|default('the string was empty', true) }}257 """258 def wrapped(env, context, value):259 if (boolean and not value) or value in (env.undefined_singleton, None):260 return default_value261 return value262 return wrapped263264265def do_join(d=u''):266 """267 Return a string which is the concatenation of the strings in the268 sequence. The separator between elements is an empty string per269 default, you can define ith with the optional parameter:270271 .. sourcecode:: jinja272273 {{ [1, 2, 3]|join('|') }}274 -> 1|2|3275276 {{ [1, 2, 3]|join }}277 -> 123278 """279 def wrapped(env, context, value):280 return env.to_unicode(d).join([env.to_unicode(x) for x in value])281 return wrapped282283284def do_count():285 """286 Return the length of the value. In case if getting an integer or float287 it will convert it into a string an return the length of the new288 string. If the object has no length it will of corse return 0.289 """290 def wrapped(env, context, value):291 try:292 if type(value) in (int, float, long):293 return len(str(value))294 return len(value)295 except TypeError:296 return 0297 return wrapped298299300def do_reverse():301 """302 Return a reversed list of the sequence filtered. You can use this303 for example for reverse iteration:304305 .. sourcecode:: jinja306307 {% for item in seq|reverse %}308 {{ item|e }}309 {% endfor %}310 """311 def wrapped(env, context, value):312 try:313 return value[::-1]314 except:315 l = list(value)316 l.reverse()317 return l318 return wrapped319320321def do_center(value, width=80):322 """323 Centers the value in a field of a given width.324 """325 return value.center(width)326do_center = stringfilter(do_center)327328329def do_first():330 """331 Return the frist item of a sequence.332 """333 def wrapped(env, context, seq):334 try:335 return iter(seq).next()336 except StopIteration:337 return env.undefined_singleton338 return wrapped339340341def do_last():342 """343 Return the last item of a sequence.344 """345 def wrapped(env, context, seq):346 try:347 return iter(reversed(seq)).next()348 except StopIteration:349 return env.undefined_singleton350 return wrapped351352353def do_random():354 """355 Return a random item from the sequence.356 """357 def wrapped(env, context, seq):358 try:359 return choice(seq)360 except IndexError:361 return env.undefined_singleton362 return wrapped363364365def do_urlencode():366 """367 urlencode a string or directory.368369 .. sourcecode:: jinja370371 {{ {'foo': 'bar', 'blub': 'blah'}|urlencode }}372 -> foo=bar&blub=blah373374 {{ 'Hello World' }}375 -> Hello%20World376 """377 def wrapped(env, context, value):378 if isinstance(value, dict):379 tmp = {}380 for key, value in value.iteritems():381 key = env.to_unicode(key).encode(env.charset)382 value = env.to_unicode(value).encode(env.charset)383 tmp[key] = value384 return urlencode(tmp)385 else:386 return quote(env.to_unicode(value).encode(env.charset))387 return wrapped388389390def do_jsonencode():391 """392 JSON dump a variable. just works if simplejson is installed.393394 .. sourcecode:: jinja395396 {{ 'Hello World'|jsonencode }}397 -> "Hello World"398 """399 global simplejson400 try:401 simplejson402 except NameError:403 import simplejson404 return lambda e, c, v: simplejson.dumps(v)405406407def do_filesizeformat():408 """409 Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102410 bytes, etc).411 """412 def wrapped(env, context, value):413 # fail silently414 try:415 bytes = float(value)416 except TypeError:417 bytes = 0418419 if bytes < 1024:420 return "%d Byte%s" % (bytes, bytes != 1 and 's' or '')421 elif bytes < 1024 * 1024:422 return "%.1f KB" % (bytes / 1024)423 elif bytes < 1024 * 1024 * 1024:424 return "%.1f MB" % (bytes / (1024 * 1024))425 return "%.1f GB" % (bytes / (1024 * 1024 * 1024))426 return wrapped427428429def do_pprint(verbose=False):430 """431 Pretty print a variable. Useful for debugging.432433 With Jinja 1.2 onwards you can pass it a parameter. If this parameter434 is truthy the output will be more verbose (this requires `pretty`)435 """436 def wrapped(env, context, value):437 return pformat(value, verbose=verbose)438 return wrapped439440441def do_urlize(value, trim_url_limit=None, nofollow=False):442 """443 Converts URLs in plain text into clickable links.444445 If you pass the filter an additional integer it will shorten the urls446 to that number. Also a third argument exists that makes the urls447 "nofollow":448449 .. sourcecode:: jinja450451 {{ mytext|urlize(40, True) }}452 links are shortened to 40 chars and defined with rel="nofollow"453 """454 return urlize(value, trim_url_limit, nofollow)455do_urlize = stringfilter(do_urlize)456457458def do_indent(s, width=4, indentfirst=False):459 """460 {{ s|indent[ width[ indentfirst[ usetab]]] }}461462 Return a copy of the passed string, each line indented by463 4 spaces. The first line is not indented. If you want to464 change the number of spaces or indent the first line too465 you can pass additional parameters to the filter:466467 .. sourcecode:: jinja468469 {{ mytext|indent(2, True) }}470 indent by two spaces and indent the first line too.471 """472 indention = ' ' * width473 if indentfirst:474 return u'\n'.join([indention + line for line in s.splitlines()])475 return s.replace('\n', '\n' + indention)476do_indent = stringfilter(do_indent)477478479def do_truncate(s, length=255, killwords=False, end='...'):480 """481 Return a truncated copy of the string. The length is specified482 with the first parameter which defaults to ``255``. If the second483 parameter is ``true`` the filter will cut the text at length. Otherwise484 it will try to save the last word. If the text was in fact485 truncated it will append an ellipsis sign (``"..."``). If you want a486 different ellipsis sign than ``"..."`` you can specify it using the487 third parameter.488489 .. sourcecode jinja::490491 {{ mytext|truncate(300, false, '&raquo;') }}492 truncate mytext to 300 chars, don't split up words, use a493 right pointing double arrow as ellipsis sign.494 """495 if len(s) <= length:496 return s497 elif killwords:498 return s[:length] + end499 words = s.split(' ')500 result = []501 m = 0502 for word in words:503 m += len(word) + 1504 if m > length:505 break506 result.append(word)507 result.append(end)508 return u' '.join(result)509do_truncate = stringfilter(do_truncate)510511512def do_wordwrap(s, pos=79, hard=False):513 """514 Return a copy of the string passed to the filter wrapped after515 ``79`` characters. You can override this default using the first516 parameter. If you set the second parameter to `true` Jinja will517 also split words apart (usually a bad idea because it makes518 reading hard).519 """520 if len(s) < pos:521 return s522 if hard:523 return u'\n'.join([s[idx:idx + pos] for idx in524 xrange(0, len(s), pos)])525 # code from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061526 return reduce(lambda line, word, pos=pos: u'%s%s%s' %527 (line, u' \n'[(len(line)-line.rfind('\n') - 1 +528 len(word.split('\n', 1)[0]) >= pos)],529 word), s.split(' '))530do_wordwrap = stringfilter(do_wordwrap)531532533def do_wordcount(s):534 """535 Count the words in that string.536 """537 return len([x for x in s.split() if x])538do_wordcount = stringfilter(do_wordcount)539540541def do_textile(s):542 """543 Prase the string using textile.544545 requires the `PyTextile`_ library.546547 .. _PyTextile: http://dealmeida.net/projects/textile/548 """549 from textile import textile550 return textile(s.encode('utf-8')).decode('utf-8')551do_textile = stringfilter(do_textile)552553554def do_markdown(s):555 """556 Parse the string using markdown.557558 requires the `Python-markdown`_ library.559560 .. _Python-markdown: http://www.freewisdom.org/projects/python-markdown/561 """562 from markdown import markdown563 return markdown(s.encode('utf-8')).decode('utf-8')564do_markdown = stringfilter(do_markdown)565566567def do_rst(s):568 """569 Parse the string using the reStructuredText parser from the570 docutils package.571572 requires `docutils`_.573574 .. _docutils: http://docutils.sourceforge.net/575 """576 from docutils.core import publish_parts577 parts = publish_parts(source=s, writer_name='html4css1')578 return parts['fragment']579do_rst = stringfilter(do_rst)580581582def do_int(default=0):583 """584 Convert the value into an integer. If the585 conversion doesn't work it will return ``0``. You can586 override this default using the first parameter.587 """588 def wrapped(env, context, value):589 try:590 return int(value)591 except (TypeError, ValueError):592 try:593 return int(float(value))594 except (TypeError, ValueError):595 return default596 return wrapped597598599def do_float(default=0.0):600 """601 Convert the value into a floating point number. If the602 conversion doesn't work it will return ``0.0``. You can603 override this default using the first parameter.604 """605 def wrapped(env, context, value):606 try:607 return float(value)608 except (TypeError, ValueError):609 return default610 return wrapped611612613def do_string():614 """615 Convert the value into an string.616 """617 return lambda e, c, v: e.to_unicode(v)618619620def do_format(*args):621 """622 Apply python string formatting on an object:623624 .. sourcecode:: jinja625626 {{ "%s - %s"|format("Hello?", "Foo!") }}627 -> Hello? - Foo!628629 Note that you cannot use the mapping syntax (``%(name)s``)630 like in python. Use `|dformat` for that.631 """632 def wrapped(env, context, value):633 return env.to_unicode(value) % args634 return wrapped635636637def do_dformat(d):638 """639 Apply python mapping string formatting on an object:640641 .. sourcecode:: jinja642643 {{ "Hello %(username)s!"|dformat({'username': 'John Doe'}) }}644 -> Hello John Doe!645646 This is useful when adding variables to translateable647 string expressions.648649 *New in Jinja 1.1*650 """651 if not isinstance(d, dict):652 raise FilterArgumentError('dict required')653 def wrapped(env, context, value):654 return env.to_unicode(value) % d655 return wrapped656657658def do_trim(value):659 """660 Strip leading and trailing whitespace.661 """662 return value.strip()663do_trim = stringfilter(do_trim)664665666def do_capture(name='captured', clean=False):667 """668 Store the value in a variable called ``captured`` or a variable669 with the name provided. Useful for filter blocks:670671 .. sourcecode:: jinja672673 {% filter capture('foo') %}674 ...675 {% endfilter %}676 {{ foo }}677678 This will output "..." two times. One time from the filter block679 and one time from the variable. If you don't want the filter to680 output something you can use it in `clean` mode:681682 .. sourcecode:: jinja683684 {% filter capture('foo', True) %}685 ...686 {% endfilter %}687 {{ foo }}688 """689 if not isinstance(name, basestring):690 raise FilterArgumentError('You can only capture into variables')691 def wrapped(env, context, value):692 context[name] = value693 if clean:694 return TemplateData()695 return value696 return wrapped697698699def do_striptags(value):700 """701 Strip SGML/XML tags and replace adjacent whitespace by one space.702703 *new in Jinja 1.1*704 """705 return ' '.join(_striptags_re.sub('', value).split())706do_striptags = stringfilter(do_striptags)707708709def do_slice(slices, fill_with=None):710 """711 Slice an iterator and return a list of lists containing712 those items. Useful if you want to create a div containing713 three div tags that represent columns:714715 .. sourcecode:: html+jinja716717 <div class="columwrapper">718 {%- for column in items|slice(3) %}719 <ul class="column-{{ loop.index }}">720 {%- for item in column %}721 <li>{{ item }}</li>722 {%- endfor %}723 </ul>724 {%- endfor %}725 </div>726727 If you pass it a second argument it's used to fill missing728 values on the last iteration.729730 *new in Jinja 1.1*731 """732 def wrapped(env, context, value):733 result = []734 seq = list(value)735 length = len(seq)736 items_per_slice = length // slices737 slices_with_extra = length % slices738 offset = 0739 for slice_number in xrange(slices):740 start = offset + slice_number * items_per_slice741 if slice_number < slices_with_extra:742 offset += 1743 end = offset + (slice_number + 1) * items_per_slice744 tmp = seq[start:end]745 if fill_with is not None and slice_number >= slices_with_extra:746 tmp.append(fill_with)747 result.append(tmp)748 return result749 return wrapped750751752def do_batch(linecount, fill_with=None):753 """754 A filter that batches items. It works pretty much like `slice`755 just the other way round. It returns a list of lists with the756 given number of items. If you provide a second parameter this757 is used to fill missing items. See this example:758759 .. sourcecode:: html+jinja760761 <table>762 {%- for row in items|batch(3, '&nbsp;') %}763 <tr>764 {%- for column in row %}765 <tr>{{ column }}</td>766 {%- endfor %}767 </tr>768 {%- endfor %}769 </table>770771 *new in Jinja 1.1*772 """773 def wrapped(env, context, value):774 result = []775 tmp = []776 for item in value:777 if len(tmp) == linecount:778 result.append(tmp)779 tmp = []780 tmp.append(item)781 if tmp:782 if fill_with is not None and len(tmp) < linecount:783 tmp += [fill_with] * (linecount - len(tmp))784 result.append(tmp)785 return result786 return wrapped787788789def do_sum():790 """791 Sum up the given sequence of numbers.792793 *new in Jinja 1.1*794 """795 def wrapped(env, context, value):796 return sum(value)797 return wrapped798799800def do_abs():801 """802 Return the absolute value of a number.803804 *new in Jinja 1.1*805 """806 def wrapped(env, context, value):807 return abs(value)808 return wrapped809810811def do_round(precision=0, method='common'):812 """813 Round the number to a given precision. The first814 parameter specifies the precision (default is ``0``), the815 second the rounding method:816817 - ``'common'`` rounds either up or down818 - ``'ceil'`` always rounds up819 - ``'floor'`` always rounds down820821 If you don't specify a method ``'common'`` is used.822823 .. sourcecode:: jinja824825 {{ 42.55|round }}826 -> 43827 {{ 42.55|round(1, 'floor') }}828 -> 42.5829830 *new in Jinja 1.1*831 """832 if not method in ('common', 'ceil', 'floor'):833 raise FilterArgumentError('method must be common, ceil or floor')834 if precision < 0:835 raise FilterArgumentError('precision must be a postive integer '836 'or zero.')837 def wrapped(env, context, value):838 if method == 'common':839 return round(value, precision)840 import math841 func = getattr(math, method)842 if precision:843 return func(value * 10 * precision) / (10 * precision)844 else:845 return func(value)846 return wrapped847848849def do_sort(reverse=False):850 """851 Sort a sequence. Per default it sorts ascending, if you pass it852 `True` as first argument it will reverse the sorting.853854 *new in Jinja 1.1*855 """856 def wrapped(env, context, value):857 return sorted(value, reverse=reverse)858 return wrapped859860861def do_groupby(attribute):862 """863 Group a sequence of objects by a common attribute.864865 If you for example have a list of dicts or objects that represent persons866 with `gender`, `first_name` and `last_name` attributes and you want to867 group all users by genders you can do something like the following868 snippet:869870 .. sourcecode:: html+jinja871872 <ul>873 {% for group in persons|groupby('gender') %}874 <li>{{ group.grouper }}<ul>875 {% for person in group.list %}876 <li>{{ person.first_name }} {{ person.last_name }}</li>877 {% endfor %}</ul></li>878 {% endfor %}879 </ul>880881 As you can see the item we're grouping by is stored in the `grouper`882 attribute and the `list` contains all the objects that have this grouper883 in common.884885 *New in Jinja 1.2*886 """887 def wrapped(env, context, value):888 expr = lambda x: env.get_attribute(x, attribute)889 return sorted([{890 'grouper': a,891 'list': list(b)892 } for a, b in groupby(sorted(value, key=expr), expr)],893 key=itemgetter('grouper'))894 return wrapped895896897def do_getattribute(attribute):898 """899 Get one attribute from an object. Normally you don't have to use this900 filter because the attribute and subscript expressions try to either901 get an attribute of an object or an item. In some situations it could902 be that there is an item *and* an attribute with the same name. In that903 situation only the item is returned, never the attribute.904905 .. sourcecode:: jinja906907 {{ foo.bar }} -> {{ foo|getattribute('bar') }}908909 *New in Jinja 1.2*910 """911 def wrapped(env, context, value):912 try:913 return get_attribute(value, attribute)914 except (SecurityException, AttributeError):915 return env.undefined_singleton916 return wrapped917918919def do_getitem(key):920 """921 This filter basically works like the normal subscript expression but922 it doesn't fall back to attribute lookup. If an item does not exist for923 an object undefined is returned.924925 .. sourcecode:: jinja926927 {{ foo.bar }} -> {{ foo|getitem('bar') }}928929 *New in Jinja 1.2*930 """931 def wrapped(env, context, value):932 try:933 return value[key]934 except (TypeError, KeyError, IndexError, AttributeError):935 return env.undefined_singleton936 return wrapped937938939FILTERS = {940 'replace': do_replace,941 'upper': do_upper,942 'lower': do_lower,943 'escape': do_escape,944 'e': do_escape,945 'xmlattr': do_xmlattr,946 'capitalize': do_capitalize,947 'title': do_title,948 'default': do_default,949 'join': do_join,950 'count': do_count,951 'dictsort': do_dictsort,952 'length': do_count,953 'reverse': do_reverse,954 'center': do_center,955 'title': do_title,956 'capitalize': do_capitalize,957 'first': do_first,958 'last': do_last,959 'random': do_random,960 'urlencode': do_urlencode,961 'jsonencode': do_jsonencode,962 'filesizeformat': do_filesizeformat,963 'pprint': do_pprint,964 'indent': do_indent,965 'truncate': do_truncate,966 'wordwrap': do_wordwrap,967 'wordcount': do_wordcount,968 'textile': do_textile,969 'markdown': do_markdown,970 'rst': do_rst,971 'int': do_int,972 'float': do_float,973 'string': do_string,974 'urlize': do_urlize,975 'format': do_format,976 'dformat': do_dformat,977 'capture': do_capture,978 'trim': do_trim,979 'striptags': do_striptags,980 'slice': do_slice,981 'batch': do_batch,982 'sum': do_sum,983 'abs': do_abs,984 'round': do_round,985 'sort': do_sort,986 'groupby': do_groupby,987 'getattribute': do_getattribute,988 'getitem': do_getitem989}
deleted:jinja/lexer.py-518 removed
1# -*- coding: utf-8 -*-2"""3 jinja.lexer4 ~~~~~~~~~~~56 This module implements a Jinja / Python combination lexer. The7 `Lexer` class provided by this module is used to do some preprocessing8 for Jinja.910 On the one hand it filters out invalid operators like the bitshift11 operators we don't allow in templates. On the other hand it separates12 template code and python code in expressions.1314 Because of some limitations in the compiler package which are just15 natural but annoying for Jinja, the lexer also "escapes" non names that16 are not keywords. The Jinja parser then removes those escaping marks17 again.1819 This is required in order to make "class" and some other python keywords20 we don't use valid identifiers.2122 :copyright: 2007-2008 by Armin Ronacher.23 :license: BSD, see LICENSE for more details.24"""25import re26import unicodedata27from jinja.datastructure import TokenStream, Token28from jinja.exceptions import TemplateSyntaxError29from jinja.utils import set, sorted30from weakref import WeakValueDictionary313233__all__ = ['Lexer', 'Failure', 'keywords']343536# cache for the lexers. Exists in order to be able to have multiple37# environments with the same lexer38_lexer_cache = WeakValueDictionary()394041# static regular expressions42whitespace_re = re.compile(r'\s+(?um)')43name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')44string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"45 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')46integer_re = re.compile(r'\d+')47float_re = re.compile(r'\d+\.\d+')48regex_re = re.compile(r'\@/([^/\\]*(?:\\.[^/\\]*)*)*/[a-z]*(?ms)')495051# set of used keywords52keywords = set(['and', 'block', 'cycle', 'elif', 'else', 'endblock',53 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',54 'endtrans', 'extends', 'filter', 'for', 'if', 'in',55 'include', 'is', 'macro', 'not', 'or', 'pluralize', 'raw',56 'recursive', 'set', 'trans', 'print', 'call', 'endcall'])5758# bind operators to token types59operators = {60 '+': 'add',61 '-': 'sub',62 '/': 'div',63 '//': 'floordiv',64 '*': 'mul',65 '%': 'mod',66 '**': 'pow',67 '~': 'tilde',68 '!': 'bang',69 '@': 'at',70 '[': 'lbracket',71 ']': 'rbracket',72 '(': 'lparen',73 ')': 'rparen',74 '{': 'lbrace',75 '}': 'rbrace',76 '==': 'eq',77 '!=': 'ne',78 '>': 'gt',79 '>=': 'gteq',80 '<': 'lt',81 '<=': 'lteq',82 '=': 'assign',83 '.': 'dot',84 ':': 'colon',85 '|': 'pipe',86 ',': 'comma'87}8889reverse_operators = dict([(v, k) for k, v in operators.iteritems()])90assert len(operators) == len(reverse_operators), 'operators dropped'91operator_re = re.compile('(%s)' % '|'.join([re.escape(x) for x in92 sorted(operators, key=lambda x: -len(x))]))9394simple_escapes = {95 'a': '\a',96 'n': '\n',97 'r': '\r',98 'f': '\f',99 't': '\t',100 'v': '\v',101 '\\': '\\',102 '"': '"',103 "'": "'",104 '0': '\x00'105}106unicode_escapes = {107 'x': 2,108 'u': 4,109 'U': 8110}111112113def unescape_string(lineno, filename, s):114 r"""115 Unescape a string. Supported escapes:116 \a, \n, \r\, \f, \v, \\, \", \', \0117118 \x00, \u0000, \U00000000, \N{...}119120 Not supported are \101 because imho redundant.121 """122 result = []123 write = result.append124 chariter = iter(s)125 next_char = chariter.next126127 # faster lookup128 sescapes = simple_escapes129 uescapes = unicode_escapes130131 try:132 for char in chariter:133 if char == '\\':134 char = next_char()135 if char in sescapes:136 write(sescapes[char])137 elif char in uescapes:138 seq = [next_char() for x in xrange(uescapes[char])]139 try:140 write(unichr(int(''.join(seq), 16)))141 except ValueError:142 raise TemplateSyntaxError('invalid unicode codepoint',143 lineno, filename)144 elif char == 'N':145 if next_char() != '{':146 raise TemplateSyntaxError('no name for codepoint',147 lineno, filename)148 seq = []149 while 1:150 char = next_char()151 if char == '}':152 break153 seq.append(char)154 try:155 write(unicodedata.lookup(u''.join(seq)))156 except KeyError:157 raise TemplateSyntaxError('unknown character name',158 lineno, filename)159 else:160 write('\\' + char)161 else:162 write(char)163 except StopIteration:164 raise TemplateSyntaxError('invalid string escape', lineno, filename)165 return u''.join(result)166167168def unescape_regex(s):169 """170 Unescape rules for regular expressions.171 """172 buffer = []173 write = buffer.append174 in_escape = False175 for char in s:176 if in_escape:177 in_escape = False178 if char not in safe_chars:179 write('\\' + char)180 continue181 write(char)182 return u''.join(buffer)183184185class Failure(object):186 """187 Class that raises a `TemplateSyntaxError` if called.188 Used by the `Lexer` to specify known errors.189 """190191 def __init__(self, message, cls=TemplateSyntaxError):192 self.message = message193 self.error_class = cls194195 def __call__(self, lineno, filename):196 raise self.error_class(self.message, lineno, filename)197198199class LexerMeta(type):200 """201 Metaclass for the lexer that caches instances for202 the same configuration in a weak value dictionary.203 """204205 def __call__(cls, environment):206 key = hash((environment.block_start_string,207 environment.block_end_string,208 environment.variable_start_string,209 environment.variable_end_string,210 environment.comment_start_string,211 environment.comment_end_string,212 environment.trim_blocks))213214 # use the cached lexer if possible215 if key in _lexer_cache:216 return _lexer_cache[key]217218 # create a new lexer and cache it219 lexer = type.__call__(cls, environment)220 _lexer_cache[key] = lexer221 return lexer222223224class Lexer(object):225 """226 Class that implements a lexer for a given environment. Automatically227 created by the environment class, usually you don't have to do that.228229 Note that the lexer is not automatically bound to an environment.230 Multiple environments can share the same lexer.231 """232233 __metaclass__ = LexerMeta234235 def __init__(self, environment):236 # shortcuts237 c = lambda x: re.compile(x, re.M | re.S)238 e = re.escape239240 # lexing rules for tags241 tag_rules = [242 (whitespace_re, None, None),243 (float_re, 'float', None),244 (integer_re, 'integer', None),245 (name_re, 'name', None),246 (string_re, 'string', None),247 (regex_re, 'regex', None),248 (operator_re, 'operator', None)249 ]250251 #: if variables and blocks have the same delimiters we won't252 #: receive any variable blocks in the parser. This variable is `True`253 #: if we need that.254 self.no_variable_block = (255 (environment.variable_start_string is256 environment.variable_end_string is None) or257 (environment.variable_start_string ==258 environment.block_start_string and259 environment.variable_end_string ==260 environment.block_end_string)261 )262263 # assamble the root lexing rule. because "|" is ungreedy264 # we have to sort by length so that the lexer continues working265 # as expected when we have parsing rules like <% for block and266 # <%= for variables. (if someone wants asp like syntax)267 # variables are just part of the rules if variable processing268 # is required.269 root_tag_rules = [270 ('comment', environment.comment_start_string),271 ('block', environment.block_start_string)272 ]273 if not self.no_variable_block:274 root_tag_rules.append(('variable',275 environment.variable_start_string))276 root_tag_rules.sort(lambda a, b: cmp(len(b[1]), len(a[1])))277278 # block suffix if trimming is enabled279 block_suffix_re = environment.trim_blocks and '\\n?' or ''280281 # global lexing rules282 self.rules = {283 'root': [284 # directives285 (c('(.*?)(?:%s)' % '|'.join(286 ['(?P<raw_begin>(?:\s*%s\-|%s)\s*raw\s*%s)' % (287 e(environment.block_start_string),288 e(environment.block_start_string),289 e(environment.block_end_string)290 )] + [291 '(?P<%s_begin>\s*%s\-|%s)' % (n, e(r), e(r))292 for n, r in root_tag_rules293 ])), ('data', '#bygroup'), '#bygroup'),294 # data295 (c('.+'), 'data', None)296 ],297 # comments298 'comment_begin': [299 (c(r'(.*?)((?:\-%s\s*|%s)%s)' % (300 e(environment.comment_end_string),301 e(environment.comment_end_string),302 block_suffix_re303 )), ('comment', 'comment_end'), '#pop'),304 (c('(.)'), (Failure('Missing end of comment tag'),), None)305 ],306 # blocks307 'block_begin': [308 (c('(?:\-%s\s*|%s)%s' % (309 e(environment.block_end_string),310 e(environment.block_end_string),311 block_suffix_re312 )), 'block_end', '#pop'),313 ] + tag_rules,314 # raw block315 'raw_begin': [316 (c('(.*?)((?:\s*%s\-|%s)\s*endraw\s*(?:\-%s\s*|%s%s))' % (317 e(environment.block_start_string),318 e(environment.block_start_string),319 e(environment.block_end_string),320 e(environment.block_end_string),321 block_suffix_re322 )), ('data', 'raw_end'), '#pop'),323 (c('(.)'), (Failure('Missing end of raw directive'),), None)324 ]325 }326327 # only add the variable rules to the list if we process variables328 # the variable_end_string variable could be None and break things.329 if not self.no_variable_block:330 self.rules['variable_begin'] = [331 (c('\-%s\s*|%s' % (332 e(environment.variable_end_string),333 e(environment.variable_end_string)334 )), 'variable_end', '#pop')335 ] + tag_rules336337 def tokenize(self, source, filename=None):338 """339 Works like `tokeniter` but returns a tokenstream of tokens and not a340 generator or token tuples. Additionally all token values are already341 converted into types and postprocessed. For example keywords are342 already keyword tokens, not named tokens, comments are removed,343 integers and floats converted, strings unescaped etc.344 """345 def generate():346 for lineno, token, value in self.tokeniter(source, filename):347 if token in ('comment_begin', 'comment', 'comment_end'):348 continue349 elif token == 'data':350 try:351 value = str(value)352 except UnicodeError:353 pass354 elif token == 'name':355 value = str(value)356 if value in keywords:357 token = value358 value = ''359 elif token == 'string':360 value = unescape_string(lineno, filename, value[1:-1])361 try:362 value = str(value)363 except UnicodeError:364 pass365 elif token == 'regex':366 args = value[value.rfind('/') + 1:]367 value = unescape_regex(value[2:-(len(args) + 1)])368 if args:369 value = '(?%s)%s' % (args, value)370 elif token == 'integer':371 value = int(value)372 elif token == 'float':373 value = float(value)374 elif token == 'operator':375 token = operators[value]376 value = ''377 yield Token(lineno, token, value)378 return TokenStream(generate(), filename)379380 def tokeniter(self, source, filename=None):381 """382 This method tokenizes the text and returns the tokens in a generator.383 Use this method if you just want to tokenize a template. The output384 you get is not compatible with the input the jinja parser wants. The385 parser uses the `tokenize` function with returns a `TokenStream` and386 keywords instead of just names.387 """388 source = '\n'.join(source.splitlines())389 pos = 0390 lineno = 1391 stack = ['root']392 statetokens = self.rules['root']393 source_length = len(source)394395 balancing_stack = []396397 while True:398 # tokenizer loop399 for regex, tokens, new_state in statetokens:400 m = regex.match(source, pos)401 # if no match we try again with the next rule402 if not m:403 continue404405 # we only match blocks and variables if brances / parentheses406 # are balanced. continue parsing with the lower rule which407 # is the operator rule. do this only if the end tags look408 # like operators409 if balancing_stack and \410 tokens in ('variable_end', 'block_end'):411 continue412413 # tuples support more options414 if isinstance(tokens, tuple):415 for idx, token in enumerate(tokens):416 # hidden group417 if token is None:418 g = m.group(idx)419 if g:420 lineno += g.count('\n')421 continue422 # failure group423 elif token.__class__ is Failure:424 raise token(lineno, filename)425 # bygroup is a bit more complex, in that case we426 # yield for the current token the first named427 # group that matched428 elif token == '#bygroup':429 for key, value in m.groupdict().iteritems():430 if value is not None:431 yield lineno, key, value432 lineno += value.count('\n')433 break434 else:435 raise RuntimeError('%r wanted to resolve '436 'the token dynamically'437 ' but no group matched'438 % regex)439 # normal group440 else:441 data = m.group(idx + 1)442 if data:443 yield lineno, token, data444 lineno += data.count('\n')445446 # strings as token just are yielded as it, but just447 # if the data is not empty448 else:449 data = m.group()450 # update brace/parentheses balance451 if tokens == 'operator':452 if data == '{':453 balancing_stack.append('}')454 elif data == '(':455 balancing_stack.append(')')456 elif data == '[':457 balancing_stack.append(']')458 elif data in ('}', ')', ']'):459 if not balancing_stack:460 raise TemplateSyntaxError('unexpected "%s"' %461 data, lineno,462 filename)463 expected_op = balancing_stack.pop()464 if expected_op != data:465 raise TemplateSyntaxError('unexpected "%s", '466 'expected "%s"' %467 (data, expected_op),468 lineno, filename)469 # yield items470 if tokens is not None:471 if data:472 yield lineno, tokens, data473 lineno += data.count('\n')474475 # fetch new position into new variable so that we can check476 # if there is a internal parsing error which would result477 # in an infinite loop478 pos2 = m.end()479480 # handle state changes481 if new_state is not None:482 # remove the uppermost state483 if new_state == '#pop':484 stack.pop()485 # resolve the new state by group checking486 elif new_state == '#bygroup':487 for key, value in m.groupdict().iteritems():488 if value is not None:489 stack.append(key)490 break491 else:492 raise RuntimeError('%r wanted to resolve the '493 'new state dynamically but'494 ' no group matched' %495 regex)496 # direct state name given497 else:498 stack.append(new_state)499 statetokens = self.rules[stack[-1]]500 # we are still at the same position and no stack change.501 # this means a loop without break condition, avoid that and502 # raise error503 elif pos2 == pos:504 raise RuntimeError('%r yielded empty string without '505 'stack change' % regex)506 # publish new function and start again507 pos = pos2508 break509 # if loop terminated without break we havn't found a single match510 # either we are at the end of the file or we have a problem511 else:512 # end of text513 if pos >= source_length:514 return515 # something went wrong516 raise TemplateSyntaxError('unexpected char %r at %d' %517 (source[pos], pos), lineno,518 filename)
deleted:jinja/loaders.py-825 removed
1# -*- coding: utf-8 -*-2"""3 jinja.loaders4 ~~~~~~~~~~~~~56 Jinja loader classes.78 :copyright: 2007 by Armin Ronacher, Bryan McLemore.9 :license: BSD, see LICENSE for more details.10"""1112import codecs13try:14 from hashlib import sha115except ImportError:16 from sha import new as sha117import time18from os import path19from threading import Lock20from jinja.parser import Parser21from jinja.translators.python import PythonTranslator, Template22from jinja.exceptions import TemplateNotFound, TemplateSyntaxError, \23 TemplateIncludeError24from jinja.utils import CacheDict252627#: when updating this, update the listing in the jinja package too28__all__ = ['FileSystemLoader', 'PackageLoader', 'DictLoader', 'ChoiceLoader',29 'FunctionLoader', 'MemcachedFileSystemLoader']303132def get_template_filename(searchpath, name):33 """34 Return the filesystem filename wanted.35 """36 for sep in path.sep, path.altsep:37 if sep and sep in name:38 name = name.replace(sep, '/')39 return path.join(searchpath, *[p for p in name.split('/')40 if p and p[0] != '.'])414243def get_cachename(cachepath, name, salt=None):44 """45 Return the filename for a cached file.46 """47 return path.join(cachepath, 'jinja_%s.cache' %48 sha1('jinja(%s|%s)tmpl' %49 (name, salt or '')).hexdigest())505152def _loader_missing(*args, **kwargs):53 """Helper function for `LoaderWrapper`."""54 raise RuntimeError('no loader defined')555657class LoaderWrapper(object):58 """59 Wraps a loader so that it's bound to an environment.60 Also handles template syntax errors.61 """6263 def __init__(self, environment, loader):64 self.environment = environment65 self.loader = loader66 if self.loader is None:67 self.get_source = self.parse = self.load = _loader_missing68 self.available = False69 else:70 self.available = True7172 def __getattr__(self, name):73 """74 Not found attributes are redirected to the loader75 """76 return getattr(self.loader, name)7778 def get_source(self, name, parent=None):79 """Retrieve the sourcecode of a template."""80 # just ascii chars are allowed as template names81 name = str(name)82 return self.loader.get_source(self.environment, name, parent)8384 def parse(self, name, parent=None):85 """Retreive a template and parse it."""86 # just ascii chars are allowed as template names87 name = str(name)88 return self.loader.parse(self.environment, name, parent)8990 def load(self, name, translator=PythonTranslator):91 """92 Translate a template and return it. This must not necesarily93 be a template class. The javascript translator for example94 will just output a string with the translated code.95 """96 # just ascii chars are allowed as template names97 name = str(name)98 try:99 return self.loader.load(self.environment, name, translator)100 except TemplateSyntaxError, e:101 if not self.environment.friendly_traceback:102 raise103 __traceback_hide__ = True104 from jinja.debugger import raise_syntax_error105 raise_syntax_error(e, self.environment)106107 def get_controlled_loader(self):108 """109 Return a loader that runs in a controlled environment. (Keeps110 track of templates that it loads and is not thread safe).111 """112 return ControlledLoader(self.environment, self.loader)113114 def _loader_missing(self, *args, **kwargs):115 """Helper method that overrides all other methods if no116 loader is defined."""117 raise RuntimeError('no loader defined')118119 def __nonzero__(self):120 return self.available121122123class ControlledLoader(LoaderWrapper):124 """125 Used for template extending and including.126 """127128 def __init__(self, environment, loader):129 LoaderWrapper.__init__(self, environment, loader)130 self._stack = []131132 def get_controlled_loader(self):133 raise TypeError('Cannot get new controlled loader from an already '134 'controlled loader.')135136 def mark_as_processed(self):137 """Mark the last parsed/sourced/included template as processed."""138 if not self._stack:139 raise RuntimeError('No template for marking found')140 self._stack.pop()141142 def _controlled(method):143 def new_method(self, name, *args, **kw):144 if name in self._stack:145 raise TemplateIncludeError('Circular imports/extends '146 'detected. %r appeared twice.' %147 name)148 self._stack.append(name)149 return method(self, name, *args, **kw)150 try:151 new_method.__name__ = method.__name__152 new_method.__doc__ = method.__doc__153 except:154 pass155 return new_method156157 get_source = _controlled(LoaderWrapper.get_source)158 parse = _controlled(LoaderWrapper.parse)159 load = _controlled(LoaderWrapper.load)160 del _controlled161162163class BaseLoader(object):164 """165 Use this class to implement loaders.166167 Just inherit from this class and implement a method called168 `get_source` with the signature (`environment`, `name`, `parent`)169 that returns sourcecode for the template.170171 For more complex loaders you probably want to override `load` to172 or not use the `BaseLoader` at all.173 """174175 def parse(self, environment, name, parent):176 """177 Load and parse a template178 """179 source = self.get_source(environment, name, parent)180 return Parser(environment, source, name).parse()181182 def load(self, environment, name, translator):183 """184 Load and translate a template185 """186 ast = self.parse(environment, name, None)187 return translator.process(environment, ast)188189 def get_source(self, environment, name, parent):190 """191 Override this method to get the source for a template.192 """193 raise TemplateNotFound(name)194195196class CachedLoaderMixin(object):197 """198 Mixin this class to implement simple memory and disk caching. The199 memcaching just uses a dict in the loader so if you have a global200 environment or at least a global loader this can speed things up.201202 If the memcaching is enabled you can use (with Jinja 1.1 onwards)203 the `clear_memcache` function to clear the cache.204205 For memcached support check the `MemcachedLoaderMixin`.206 """207208 def __init__(self, use_memcache, cache_size, cache_folder, auto_reload,209 cache_salt=None):210 if use_memcache:211 self.__memcache = CacheDict(cache_size)212 else:213 self.__memcache = None214 self.__cache_folder = cache_folder215 if not hasattr(self, 'check_source_changed'):216 self.__auto_reload = False217 else:218 self.__auto_reload = auto_reload219 self.__salt = cache_salt220 self.__times = {}221 self.__lock = Lock()222223 def clear_memcache(self):224 """225 Clears the memcache.226 """227 if self.__memcache is not None:228 self.__memcache.clear()229230 def load(self, environment, name, translator):231 """232 Load and translate a template. First we check if there is a233 cached version of this template in the memory cache. If this is234 not the cache check for a compiled template in the disk cache235 folder. And if none of this is the case we translate the temlate,236 cache and return it.237 """238 self.__lock.acquire()239 try:240 # caching is only possible for the python translator. skip241 # all other translators242 if not issubclass(translator, PythonTranslator):243 return super(CachedLoaderMixin, self).load(244 environment, name, translator)245246 tmpl = None247 save_to_disk = False248 push_to_memory = False249250 # auto reload enabled? check for the last change of251 # the template252 if self.__auto_reload:253 last_change = self.check_source_changed(environment, name)254 else:255 last_change = None256257 # check if we have something in the memory cache and the258 # memory cache is enabled.259 if self.__memcache is not None:260 if name in self.__memcache:261 tmpl = self.__memcache[name]262 # if auto reload is enabled check if the template changed263 if last_change and last_change > self.__times[name]:264 tmpl = None265 push_to_memory = True266 else:267 push_to_memory = True268269 # mem cache disabled or not cached by now270 # try to load if from the disk cache271 if tmpl is None and self.__cache_folder is not None:272 cache_fn = get_cachename(self.__cache_folder, name, self.__salt)273 if last_change is not None:274 try:275 cache_time = path.getmtime(cache_fn)276 except OSError:277 cache_time = 0278 if last_change is None or (cache_time and279 last_change <= cache_time):280 try:281 f = file(cache_fn, 'rb')282 except IOError:283 tmpl = None284 save_to_disk = True285 else:286 try:287 tmpl = Template.load(environment, f)288 finally:289 f.close()290 else:291 save_to_disk = True292293 # if we still have no template we load, parse and translate it.294 if tmpl is None:295 tmpl = super(CachedLoaderMixin, self).load(296 environment, name, translator)297298 # save the compiled template on the disk if enabled299 if save_to_disk:300 f = file(cache_fn, 'wb')301 try:302 tmpl.dump(f)303 finally:304 f.close()305306 # if memcaching is enabled and the template not loaded307 # we add that there.308 if push_to_memory:309 self.__times[name] = time.time()310 self.__memcache[name] = tmpl311 return tmpl312 finally:313 self.__lock.release()314315316class MemcachedLoaderMixin(object):317 """318 Uses a memcached server to cache the templates.319320 Requires the memcache library from `tummy`_ or the cmemcache library321 from `Gijsbert de Haan`_.322323 With Jinja 1.2 onwards you can also provide a `client` keyword argument324 that takes an already instanciated memcache client or memcache client325 like object.326327 .. _tummy: http://www.tummy.com/Community/software/python-memcached/328 .. _Gisjsbert de Haan: http://gijsbert.org/cmemcache/329 """330331 def __init__(self, use_memcache, memcache_time=60 * 60 * 24 * 7,332 memcache_host=None, item_prefix='template/', client=None):333 if memcache_host is None:334 memcache_host = ['127.0.0.1:11211']335 if use_memcache:336 if client is None:337 try:338 try:339 from cmemcache import Client340 except ImportError:341 from memcache import Client342 except ImportError:343 raise RuntimeError('the %r loader requires an installed '344 'memcache module' %345 self.__class__.__name__)346 client = Client(list(memcache_host))347 self.__memcache = client348 self.__memcache_time = memcache_time349 else:350 self.__memcache = None351 self.__item_prefix = item_prefix352 self.__lock = Lock()353354 def load(self, environment, name, translator):355 """356 Load and translate a template. First we check if there is a357 cached version of this template in the memory cache. If this is358 not the cache check for a compiled template in the disk cache359 folder. And if none of this is the case we translate the template,360 cache and return it.361 """362 self.__lock.acquire()363 try:364 # caching is only possible for the python translator. skip365 # all other translators366 if not issubclass(translator, PythonTranslator):367 return super(MemcachedLoaderMixin, self).load(368 environment, name, translator)369 tmpl = None370 push_to_memory = False371372 # check if we have something in the memory cache and the373 # memory cache is enabled.374 if self.__memcache is not None:375 bytecode = self.__memcache.get(self.__item_prefix + name)376 if bytecode:377 tmpl = Template.load(environment, bytecode)378 else:379 push_to_memory = True380381 # if we still have no template we load, parse and translate it.382 if tmpl is None:383 tmpl = super(MemcachedLoaderMixin, self).load(384 environment, name, translator)385386 # if memcaching is enabled and the template not loaded387 # we add that there.388 if push_to_memory:389 self.__memcache.set(self.__item_prefix + name, tmpl.dump(),390 self.__memcache_time)391 return tmpl392 finally:393 self.__lock.release()394395396class BaseFileSystemLoader(BaseLoader):397 """398 Baseclass for the file system loader that does not do any caching.399 It exists to avoid redundant code, just don't use it without subclassing.400401 How subclassing can work:402403 .. sourcecode:: python404405 from jinja.loaders import BaseFileSystemLoader406407 class MyFileSystemLoader(BaseFileSystemLoader):408 def __init__(self):409 BaseFileSystemLoader.__init__(self, '/path/to/templates')410411 The base file system loader only takes one parameter beside self which412 is the path to the templates.413 """414415 def __init__(self, searchpath):416 self.searchpath = path.abspath(searchpath)417418 def get_source(self, environment, name, parent):419 filename = get_template_filename(self.searchpath, name)420 if path.isfile(filename):421 f = codecs.open(filename, 'r', environment.template_charset)422 try:423 return f.read()424 finally:425 f.close()426 else:427 raise TemplateNotFound(name)428429430class FileSystemLoader(CachedLoaderMixin, BaseFileSystemLoader):431 """432 Loads templates from the filesystem:433434 .. sourcecode:: python435436 from jinja import Environment, FileSystemLoader437 e = Environment(loader=FileSystemLoader('templates/'))438439 You can pass the following keyword arguments to the loader on440 initialization:441442 =================== =================================================443 ``searchpath`` String with the path to the templates on the444 filesystem.445 ``use_memcache`` Set this to ``True`` to enable memory caching.446 This is usually a good idea in production mode,447 but disable it during development since it won't448 reload template changes automatically.449 This only works in persistent environments like450 FastCGI.451 ``memcache_size`` Number of template instance you want to cache.452 Defaults to ``40``.453 ``cache_folder`` Set this to an existing directory to enable454 caching of templates on the file system. Note455 that this only affects templates transformed456 into python code. Default is ``None`` which means457 that caching is disabled.458 ``auto_reload`` Set this to `False` for a slightly better459 performance. In that case Jinja won't check for460 template changes on the filesystem.461 ``cache_salt`` Optional unique number to not confuse the462 caching system when caching more than one463 template loader in the same folder. Defaults464 to the searchpath. *New in Jinja 1.1*465 =================== =================================================466 """467468 def __init__(self, searchpath, use_memcache=False, memcache_size=40,469 cache_folder=None, auto_reload=True, cache_salt=None):470 BaseFileSystemLoader.__init__(self, searchpath)471472 if cache_salt is None:473 cache_salt = self.searchpath474 CachedLoaderMixin.__init__(self, use_memcache, memcache_size,475 cache_folder, auto_reload, cache_salt)476477 def check_source_changed(self, environment, name):478 filename = get_template_filename(self.searchpath, name)479 if path.isfile(filename):480 return path.getmtime(filename)481 return -1482483484class MemcachedFileSystemLoader(MemcachedLoaderMixin, BaseFileSystemLoader):485 """486 Loads templates from the filesystem and caches them on a memcached487 server.488489 .. sourcecode:: python490491 from jinja import Environment, MemcachedFileSystemLoader492 e = Environment(loader=MemcachedFileSystemLoader('templates/',493 memcache_host=['192.168.2.250:11211']494 ))495496 You can pass the following keyword arguments to the loader on497 initialization:498499 =================== =================================================500 ``searchpath`` String with the path to the templates on the501 filesystem.502 ``use_memcache`` Set this to ``True`` to enable memcached caching.503 In that case it behaves like a normal504 `FileSystemLoader` with disabled caching.505 ``memcache_time`` The expire time of a template in the cache.506 ``memcache_host`` a list of memcached servers.507 ``item_prefix`` The prefix for the items on the server. Defaults508 to ``'template/'``.509 =================== =================================================510 """511512 def __init__(self, searchpath, use_memcache=True,513 memcache_time=60 * 60 * 24 * 7, memcache_host=None,514 item_prefix='template/'):515 BaseFileSystemLoader.__init__(self, searchpath)516 MemcachedLoaderMixin.__init__(self, use_memcache, memcache_time,517 memcache_host, item_prefix)518519520class BasePackageLoader(BaseLoader):521 """522 Baseclass for the package loader that does not do any caching.523524 It accepts two parameters: The name of the package and the path relative525 to the package:526527 .. sourcecode:: python528529 from jinja.loaders import BasePackageLoader530531 class MyPackageLoader(BasePackageLoader):532 def __init__(self):533 BasePackageLoader.__init__(self, 'my_package', 'shared/templates')534535 The relative path must use slashes as path delimiters, even on Mac OS536 and Microsoft Windows.537538 It uses the `pkg_resources` libraries distributed with setuptools for539 retrieving the data from the packages. This works for eggs too so you540 don't have to mark your egg as non zip safe. If pkg_resources is not541 available it just falls back to path joining relative to the package.542 """543544 def __init__(self, package_name, package_path, force_native=False):545 try:546 import pkg_resources547 except ImportError:548 raise RuntimeError('setuptools not installed')549 self.package_name = package_name550 self.package_path = package_path551 self.force_native = force_native552553 def _get_load_func(self):554 if hasattr(self, '_load_func'):555 return self._load_func556 try:557 from pkg_resources import resource_exists, resource_string558 if self.force_native:559 raise ImportError()560 except ImportError:561 basepath = path.dirname(__import__(self.package_name, None, None,562 ['__file__']).__file__)563 def load_func(name):564 filename = path.join(basepath, *(565 self.package_path.split('/') +566 [p for p in name.split('/') if p != '..'])567 )568 if path.isfile(filename):569 f = file(filename)570 try:571 return f.read()572 finally:573 f.close()574 else:575 def load_func(name):576 path = '/'.join([self.package_path] + [p for p in name.split('/')577 if p != '..'])578 if resource_exists(self.package_name, path):579 return resource_string(self.package_name, path)580 self._load_func = load_func581 return load_func582583 def get_source(self, environment, name, parent):584 load_func = self._get_load_func()585 contents = load_func(name)586 if contents is None:587 raise TemplateNotFound(name)588 return contents.decode(environment.template_charset)589590591class PackageLoader(CachedLoaderMixin, BasePackageLoader):592 """593 Loads templates from python packages using setuptools.594595 .. sourcecode:: python596597 from jinja import Environment, PackageLoader598 e = Environment(loader=PackageLoader('yourapp', 'template/path'))599600 You can pass the following keyword arguments to the loader on601 initialization:602603 =================== =================================================604 ``package_name`` Name of the package containing the templates.605 ``package_path`` Path of the templates inside the package.606 ``use_memcache`` Set this to ``True`` to enable memory caching.607 This is usually a good idea in production mode,608 but disable it during development since it won't609 reload template changes automatically.610 This only works in persistent environments like611 FastCGI.612 ``memcache_size`` Number of template instance you want to cache.613 Defaults to ``40``.614 ``cache_folder`` Set this to an existing directory to enable615 caching of templates on the file system. Note616 that this only affects templates transformed617 into python code. Default is ``None`` which means618 that caching is disabled.619 ``auto_reload`` Set this to `False` for a slightly better620 performance. In that case Jinja won't check for621 template changes on the filesystem. If the622 templates are inside of an egg file this won't623 have an effect.624 ``cache_salt`` Optional unique number to not confuse the625 caching system when caching more than one626 template loader in the same folder. Defaults627 to ``package_name + '/' + package_path``.628 *New in Jinja 1.1*629 =================== =================================================630631 Important note: If you're using an application that is inside of an632 egg never set `auto_reload` to `True`. The egg resource manager will633 automatically export files to the file system and touch them so that634 you not only end up with additional temporary files but also an automatic635 reload each time you load a template.636 """637638 def __init__(self, package_name, package_path, use_memcache=False,639 memcache_size=40, cache_folder=None, auto_reload=True,640 cache_salt=None):641 BasePackageLoader.__init__(self, package_name, package_path)642643 if cache_salt is None:644 cache_salt = package_name + '/' + package_path645 CachedLoaderMixin.__init__(self, use_memcache, memcache_size,646 cache_folder, auto_reload, cache_salt)647648 def check_source_changed(self, environment, name):649 from pkg_resources import resource_exists, resource_filename650 fn = resource_filename(self.package_name, '/'.join([self.package_path] +651 [p for p in name.split('/') if p and p[0] != '.']))652 if resource_exists(self.package_name, fn):653 return path.getmtime(fn)654 return -1655656657class BaseFunctionLoader(BaseLoader):658 """659 Baseclass for the function loader that doesn't do any caching.660661 It just accepts one parameter which is the function which is called662 with the name of the requested template. If the return value is `None`663 the loader will raise a `TemplateNotFound` error.664665 .. sourcecode:: python666667 from jinja.loaders import BaseFunctionLoader668669 templates = {...}670671 class MyFunctionLoader(BaseFunctionLoader):672 def __init__(self):673 BaseFunctionLoader(templates.get)674 """675676 def __init__(self, loader_func):677 self.loader_func = loader_func678679 def get_source(self, environment, name, parent):680 rv = self.loader_func(name)681 if rv is None:682 raise TemplateNotFound(name)683 if isinstance(rv, str):684 return rv.decode(environment.template_charset)685 return rv686687688class FunctionLoader(CachedLoaderMixin, BaseFunctionLoader):689 """690 Loads templates by calling a function which has to return a string691 or `None` if an error occoured.692693 .. sourcecode:: python694695 from jinja import Environment, FunctionLoader696697 def my_load_func(template_name):698 if template_name == 'foo':699 return '...'700701 e = Environment(loader=FunctionLoader(my_load_func))702703 Because the interface is limited there is no way to cache such704 templates. Usually you should try to use a loader with a more705 solid backend.706707 You can pass the following keyword arguments to the loader on708 initialization:709710 =================== =================================================711 ``loader_func`` Function that takes the name of the template to712 load. If it returns a string or unicode object713 it's used to load a template. If the return714 value is None it's considered missing.715 ``getmtime_func`` Function used to check if templates requires716 reloading. Has to return the UNIX timestamp of717 the last template change or ``-1`` if this template718 does not exist or requires updates at any cost.719 ``use_memcache`` Set this to ``True`` to enable memory caching.720 This is usually a good idea in production mode,721 but disable it during development since it won't722 reload template changes automatically.723 This only works in persistent environments like724 FastCGI.725 ``memcache_size`` Number of template instance you want to cache.726 Defaults to ``40``.727 ``cache_folder`` Set this to an existing directory to enable728 caching of templates on the file system. Note729 that this only affects templates transformed730 into python code. Default is ``None`` which means731 that caching is disabled.732 ``auto_reload`` Set this to `False` for a slightly better733 performance. In that case of `getmtime_func`734 not being provided this won't have an effect.735 ``cache_salt`` Optional unique number to not confuse the736 caching system when caching more than one737 template loader in the same folder.738 =================== =================================================739 """740741 def __init__(self, loader_func, getmtime_func=None, use_memcache=False,742 memcache_size=40, cache_folder=None, auto_reload=True,743 cache_salt=None):744 BaseFunctionLoader.__init__(self, loader_func)745 # when changing the signature also check the jinja.plugin function746 # loader instantiation.747 self.getmtime_func = getmtime_func748 if auto_reload and getmtime_func is None:749 auto_reload = False750 CachedLoaderMixin.__init__(self, use_memcache, memcache_size,751 cache_folder, auto_reload, cache_salt)752753 def check_source_changed(self, environment, name):754 return self.getmtime_func(name)755756757class DictLoader(BaseLoader):758 """759 Load templates from a given dict:760761 .. sourcecode:: python762763 from jinja import Environment, DictLoader764 e = Environment(loader=DictLoader(dict(765 layout='...',766 index='{% extends 'layout' %}...'767 )))768769 This loader does not have any caching capabilities.770 """771772 def __init__(self, templates):773 self.templates = templates774775 def get_source(self, environment, name, parent):776 if name in self.templates:777 return self.templates[name]778 raise TemplateNotFound(name)779780781class ChoiceLoader(object):782 """783 A loader that tries multiple loaders in the order they are given to784 the `ChoiceLoader`:785786 .. sourcecode:: python787788 from jinja import ChoiceLoader, FileSystemLoader789 loader1 = FileSystemLoader("templates1")790 loader2 = FileSystemLoader("templates2")791 loader = ChoiceLoader([loader1, loader2])792 """793794 def __init__(self, loaders):795 self.loaders = list(loaders)796797 def get_source(self, environment, name, parent):798 for loader in self.loaders:799 try:800 return loader.get_source(environment, name, parent)801 except TemplateNotFound, e:802 if e.name != name:803 raise804 continue805 raise TemplateNotFound(name)806807 def parse(self, environment, name, parent):808 for loader in self.loaders:809 try:810 return loader.parse(environment, name, parent)811 except TemplateNotFound, e:812 if e.name != name:813 raise814 continue815 raise TemplateNotFound(name)816817 def load(self, environment, name, translator):818 for loader in self.loaders:819 try:820 return loader.load(environment, name, translator)821 except TemplateNotFound, e:822 if e.name != name:823 raise824 continue825 raise TemplateNotFound(name)
deleted:jinja/nodes.py-792 removed
1# -*- coding: utf-8 -*-2"""3 jinja.nodes4 ~~~~~~~~~~~56 This module implements additional nodes derived from the ast base node.78 It also provides some node tree helper functions like `in_lineno` and9 `get_nodes` used by the parser and translator in order to normalize10 python and jinja nodes.1112 :copyright: 2007 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14"""15from itertools import chain16from copy import copy171819def get_nodes(nodetype, tree, exclude_root=True):20 """21 Get all nodes from nodetype in the tree excluding the22 node passed if `exclude_root` is `True` (default).23 """24 if exclude_root:25 todo = tree.get_child_nodes()26 else:27 todo = [tree]28 while todo:29 node = todo.pop()30 if node.__class__ is nodetype:31 yield node32 todo.extend(node.get_child_nodes())333435class NotPossible(NotImplementedError):36 """37 If a given node cannot do something.38 """394041class Node(object):42 """43 Jinja node.44 """4546 def __init__(self, lineno=None, filename=None):47 self.lineno = lineno48 self.filename = filename4950 def get_items(self):51 return []5253 def get_child_nodes(self):54 return [x for x in self.get_items() if isinstance(x, Node)]5556 def allows_assignments(self):57 return False5859 def __repr__(self):60 return 'Node()'616263class Text(Node):64 """65 Node that represents normal text.66 """6768 def __init__(self, text, variables, lineno=None, filename=None):69 Node.__init__(self, lineno, filename)70 self.text = text71 self.variables = variables7273 def get_items(self):74 return [self.text] + list(self.variables)7576 def __repr__(self):77 return 'Text(%r, %r)' % (78 self.text,79 self.variables80 )818283class NodeList(list, Node):84 """85 A node that stores multiple childnodes.86 """8788 def __init__(self, data, lineno=None, filename=None):89 Node.__init__(self, lineno, filename)90 list.__init__(self, data)9192 def get_items(self):93 return list(self)9495 def __repr__(self):96 return 'NodeList(%s)' % list.__repr__(self)979899class Template(Node):100 """101 Node that represents a template.102 """103104 def __init__(self, extends, body, lineno=None, filename=None):105 Node.__init__(self, lineno, filename)106 self.extends = extends107 self.body = body108109 def get_items(self):110 return [self.extends, self.body]111112 def __repr__(self):113 return 'Template(%r, %r)' % (114 self.extends,115 self.body116 )117118119class ForLoop(Node):120 """121 A node that represents a for loop122 """123124 def __init__(self, item, seq, body, else_, recursive, lineno=None,125 filename=None):126 Node.__init__(self, lineno, filename)127 self.item = item128 self.seq = seq129 self.body = body130 self.else_ = else_131 self.recursive = recursive132133 def get_items(self):134 return [self.item, self.seq, self.body, self.else_, self.recursive]135136 def __repr__(self):137 return 'ForLoop(%r, %r, %r, %r, %r)' % (138 self.item,139 self.seq,140 self.body,141 self.else_,142 self.recursive143 )144145146class IfCondition(Node):147 """148 A node that represents an if condition.149 """150151 def __init__(self, tests, else_, lineno=None, filename=None):152 Node.__init__(self, lineno, filename)153 self.tests = tests154 self.else_ = else_155156 def get_items(self):157 result = []158 for test in self.tests:159 result.extend(test)160 result.append(self.else_)161 return result162163 def __repr__(self):164 return 'IfCondition(%r, %r)' % (165 self.tests,166 self.else_167 )168169170class Cycle(Node):171 """172 A node that represents the cycle statement.173 """174175 def __init__(self, seq, lineno=None, filename=None):176 Node.__init__(self, lineno, filename)177 self.seq = seq178179 def get_items(self):180 return [self.seq]181182 def __repr__(self):183 return 'Cycle(%r)' % (self.seq,)184185186class Print(Node):187 """188 A node that represents variable tags and print calls.189 """190191 def __init__(self, expr, lineno=None, filename=None):192 Node.__init__(self, lineno, filename)193 self.expr = expr194195 def get_items(self):196 return [self.expr]197198 def __repr__(self):199 return 'Print(%r)' % (self.expr,)200201202class Macro(Node):203 """204 A node that represents a macro.205 """206207 def __init__(self, name, arguments, body, lineno=None, filename=None):208 Node.__init__(self, lineno, filename)209 self.name = name210 self.arguments = arguments211 self.body = body212213 def get_items(self):214 return [self.name] + list(chain(*self.arguments)) + [self.body]215216 def __repr__(self):217 return 'Macro(%r, %r, %r)' % (218 self.name,219 self.arguments,220 self.body221 )222223224class Call(Node):225 """226 A node that represents am extended macro call.227 """228229 def __init__(self, expr, body, lineno=None, filename=None):230 Node.__init__(self, lineno, filename)231 self.expr = expr232 self.body = body233234 def get_items(self):235 return [self.expr, self.body]236237 def __repr__(self):238 return 'Call(%r, %r)' % (239 self.expr,240 self.body241 )242243244class Set(Node):245 """246 Allows defining own variables.247 """248249 def __init__(self, name, expr, scope_local, lineno=None, filename=None):250 Node.__init__(self, lineno, filename)251 self.name = name252 self.expr = expr253 self.scope_local = scope_local254255 def get_items(self):256 return [self.name, self.expr, self.scope_local]257258 def __repr__(self):259 return 'Set(%r, %r, %r)' % (260 self.name,261 self.expr,262 self.scope_local263 )264265266class Filter(Node):267 """268 Node for filter sections.269 """270271 def __init__(self, body, filters, lineno=None, filename=None):272 Node.__init__(self, lineno, filename)273 self.body = body274 self.filters = filters275276 def get_items(self):277 return [self.body] + list(self.filters)278279 def __repr__(self):280 return 'Filter(%r, %r)' % (281 self.body,282 self.filters283 )284285286class Block(Node):287 """288 A node that represents a block.289 """290291 def __init__(self, name, body, lineno=None, filename=None):292 Node.__init__(self, lineno, filename)293 self.name = name294 self.body = body295296 def replace(self, node):297 """298 Replace the current data with the copied data of another block299 node.300 """301 assert node.__class__ is Block302 self.lineno = node.lineno303 self.filename = node.filename304 self.name = node.name305 self.body = copy(node.body)306307 def clone(self):308 """309 Create an independent clone of this node.310 """311 return copy(self)312313 def get_items(self):314 return [self.name, self.body]315316 def __repr__(self):317 return 'Block(%r, %r)' % (318 self.name,319 self.body320 )321322323class Include(Node):324 """325 A node that represents the include tag.326 """327328 def __init__(self, template, lineno=None, filename=None):329 Node.__init__(self, lineno, filename)330 self.template = template331332 def get_items(self):333 return [self.template]334335 def __repr__(self):336 return 'Include(%r)' % (337 self.template338 )339340341class Trans(Node):342 """343 A node for translatable sections.344 """345346 def __init__(self, singular, plural, indicator, replacements,347 lineno=None, filename=None):348 Node.__init__(self, lineno, filename)349 self.singular = singular350 self.plural = plural351 self.indicator = indicator352 self.replacements = replacements353354 def get_items(self):355 rv = [self.singular, self.plural, self.indicator]356 if self.replacements:357 rv.extend(self.replacements.values())358 rv.extend(self.replacements.keys())359 return rv360361 def __repr__(self):362 return 'Trans(%r, %r, %r, %r)' % (363 self.singular,364 self.plural,365 self.indicator,366 self.replacements367 )368369370class Expression(Node):371 """372 Baseclass for all expressions.373 """374375376class BinaryExpression(Expression):377 """378 Baseclass for all binary expressions.379 """380381 def __init__(self, left, right, lineno=None, filename=None):382 Expression.__init__(self, lineno, filename)383 self.left = left384 self.right = right385386 def get_items(self):387 return [self.left, self.right]388389 def __repr__(self):390 return '%s(%r, %r)' % (391 self.__class__.__name__,392 self.left,393 self.right394 )395396397class UnaryExpression(Expression):398 """399 Baseclass for all unary expressions.400 """401402 def __init__(self, node, lineno=None, filename=None):403 Expression.__init__(self, lineno, filename)404 self.node = node405406 def get_items(self):407 return [self.node]408409 def __repr__(self):410 return '%s(%r)' % (411 self.__class__.__name__,412 self.node413 )414415416class ConstantExpression(Expression):417 """418 any constat such as {{ "foo" }}419 """420421 def __init__(self, value, lineno=None, filename=None):422 Expression.__init__(self, lineno, filename)423 self.value = value424425 def get_items(self):426 return [self.value]427428 def __repr__(self):429 return 'ConstantExpression(%r)' % (self.value,)430431432class UndefinedExpression(Expression):433 """434 represents the special 'undefined' value.435 """436437 def __repr__(self):438 return 'UndefinedExpression()'439440441class RegexExpression(Expression):442 """443 represents the regular expression literal.444 """445446 def __init__(self, value, lineno=None, filename=None):447 Expression.__init__(self, lineno, filename)448 self.value = value449450 def get_items(self):451 return [self.value]452453 def __repr__(self):454 return 'RegexExpression(%r)' % (self.value,)455456457class NameExpression(Expression):458 """459 any name such as {{ foo }}460 """461462 def __init__(self, name, lineno=None, filename=None):463 Expression.__init__(self, lineno, filename)464 self.name = name465466 def get_items(self):467 return [self.name]468469 def allows_assignments(self):470 return self.name != '_'471472 def __repr__(self):473 return 'NameExpression(%r)' % self.name474475476class ListExpression(Expression):477 """478 any list literal such as {{ [1, 2, 3] }}479 """480481 def __init__(self, items, lineno=None, filename=None):482 Expression.__init__(self, lineno, filename)483 self.items = items484485 def get_items(self):486 return list(self.items)487488 def __repr__(self):489 return 'ListExpression(%r)' % (self.items,)490491492class DictExpression(Expression):493 """494 any dict literal such as {{ {1: 2, 3: 4} }}495 """496497 def __init__(self, items, lineno=None, filename=None):498 Expression.__init__(self, lineno, filename)499 self.items = items500501 def get_items(self):502 return list(chain(*self.items))503504 def __repr__(self):505 return 'DictExpression(%r)' % (self.items,)506507508class SetExpression(Expression):509 """510 any set literal such as {{ @(1, 2, 3) }}511 """512513 def __init__(self, items, lineno=None, filename=None):514 Expression.__init__(self, lineno, filename)515 self.items = items516517 def get_items(self):518 return self.items[:]519520 def __repr__(self):521 return 'SetExpression(%r)' % (self.items,)522523524class ConditionalExpression(Expression):525 """526 {{ foo if bar else baz }}527 """528529 def __init__(self, test, expr1, expr2, lineno=None, filename=None):530 Expression.__init__(self, lineno, filename)531 self.test = test532 self.expr1 = expr1533 self.expr2 = expr2534535 def get_items(self):536 return [self.test, self.expr1, self.expr2]537538 def __repr__(self):539 return 'ConstantExpression(%r, %r, %r)' % (540 self.test,541 self.expr1,542 self.expr2543 )544545546class FilterExpression(Expression):547 """548 {{ foo|bar|baz }}549 """550551 def __init__(self, node, filters, lineno=None, filename=None):552 Expression.__init__(self, lineno, filename)553 self.node = node554 self.filters = filters555556 def get_items(self):557 result = [self.node]558 for filter, args in self.filters:559 result.append(filter)560 result.extend(args)561 return result562563 def __repr__(self):564 return 'FilterExpression(%r, %r)' % (565 self.node,566 self.filters567 )568569570class TestExpression(Expression):571 """572 {{ foo is lower }}573 """574575 def __init__(self, node, name, args, lineno=None, filename=None):576 Expression.__init__(self, lineno, filename)577 self.node = node578 self.name = name579 self.args = args580581 def get_items(self):582 return [self.node, self.name] + list(self.args)583584 def __repr__(self):585 return 'TestExpression(%r, %r, %r)' % (586 self.node,587 self.name,588 self.args589 )590591592class CallExpression(Expression):593 """594 {{ foo(bar) }}595 """596597 def __init__(self, node, args, kwargs, dyn_args, dyn_kwargs,598 lineno=None, filename=None):599 Expression.__init__(self, lineno, filename)600 self.node = node601 self.args = args602 self.kwargs = kwargs603 self.dyn_args = dyn_args604 self.dyn_kwargs = dyn_kwargs605606 def get_items(self):607 return [self.node, self.args, self.kwargs, self.dyn_args,608 self.dyn_kwargs]609610 def __repr__(self):611 return 'CallExpression(%r, %r, %r, %r, %r)' % (612 self.node,613 self.args,614 self.kwargs,615 self.dyn_args,616 self.dyn_kwargs617 )618619620class SubscriptExpression(Expression):621 """622 {{ foo.bar }} and {{ foo['bar'] }} etc.623 """624625 def __init__(self, node, arg, lineno=None, filename=None):626 Expression.__init__(self, lineno, filename)627 self.node = node628 self.arg = arg629630 def get_items(self):631 return [self.node, self.arg]632633 def __repr__(self):634 return 'SubscriptExpression(%r, %r)' % (635 self.node,636 self.arg637 )638639640class SliceExpression(Expression):641 """642 1:2:3 etc.643 """644645 def __init__(self, start, stop, step, lineno=None, filename=None):646 Expression.__init__(self, lineno, filename)647 self.start = start648 self.stop = stop649 self.step = step650651 def get_items(self):652 return [self.start, self.stop, self.step]653654 def __repr__(self):655 return 'SliceExpression(%r, %r, %r)' % (656 self.start,657 self.stop,658 self.step659 )660661662class TupleExpression(Expression):663 """664 For loop unpacking and some other things like multiple arguments665 for subscripts.666 """667668 def __init__(self, items, lineno=None, filename=None):669 Expression.__init__(self, lineno, filename)670 self.items = items671672 def get_items(self):673 return list(self.items)674675 def allows_assignments(self):676 for item in self.items:677 if not item.allows_assignments():678 return False679 return True680681 def __repr__(self):682 return 'TupleExpression(%r)' % (self.items,)683684685class ConcatExpression(Expression):686 """687 For {{ foo ~ bar }}. Because of various reasons (especially because688 unicode conversion takes place for the left and right expression and689 is better optimized that way)690 """691692 def __init__(self, args, lineno=None, filename=None):693 Expression.__init__(self, lineno, filename)694 self.args = args695696 def get_items(self):697 return list(self.args)698699 def __repr__(self):700 return 'ConcatExpression(%r)' % (self.items,)701702703class CompareExpression(Expression):704 """705 {{ foo == bar }}, {{ foo >= bar }} etc.706 """707708 def __init__(self, expr, ops, lineno=None, filename=None):709 Expression.__init__(self, lineno, filename)710 self.expr = expr711 self.ops = ops712713 def get_items(self):714 return [self.expr] + list(chain(*self.ops))715716 def __repr__(self):717 return 'CompareExpression(%r, %r)' % (718 self.expr,719 self.ops720 )721722723class MulExpression(BinaryExpression):724 """725 {{ foo * bar }}726 """727728729class DivExpression(BinaryExpression):730 """731 {{ foo / bar }}732 """733734735class FloorDivExpression(BinaryExpression):736 """737 {{ foo // bar }}738 """739740741class AddExpression(BinaryExpression):742 """743 {{ foo + bar }}744 """745746747class SubExpression(BinaryExpression):748 """749 {{ foo - bar }}750 """751752753class ModExpression(BinaryExpression):754 """755 {{ foo % bar }}756 """757758759class PowExpression(BinaryExpression):760 """761 {{ foo ** bar }}762 """763764765class AndExpression(BinaryExpression):766 """767 {{ foo and bar }}768 """769770771class OrExpression(BinaryExpression):772 """773 {{ foo or bar }}774 """775776777class NotExpression(UnaryExpression):778 """779 {{ not foo }}780 """781782783class NegExpression(UnaryExpression):784 """785 {{ -foo }}786 """787788789class PosExpression(UnaryExpression):790 """791 {{ +foo }}792 """
deleted:jinja/parser.py-1187 removed
1# -*- coding: utf-8 -*-2"""3 jinja.parser4 ~~~~~~~~~~~~56 Implements the template parser.78 The Jinja template parser is not a real parser but a combination of the9 python compiler package and some postprocessing. The tokens yielded by10 the lexer are used to separate template data and expressions. The11 expression tokens are then converted into strings again and processed12 by the python parser.1314 :copyright: 2007 by Armin Ronacher.15 :license: BSD, see LICENSE for more details.16"""17from jinja import nodes18from jinja.datastructure import StateTest19from jinja.exceptions import TemplateSyntaxError20from jinja.utils import set212223__all__ = ['Parser']242526# general callback functions for the parser27end_of_block = StateTest.expect_token('block_end',28 msg='expected end of block tag')29end_of_variable = StateTest.expect_token('variable_end',30 msg='expected end of variable')31end_of_comment = StateTest.expect_token('comment_end',32 msg='expected end of comment')3334# internal tag callbacks35switch_for = StateTest.expect_token('else', 'endfor')36end_of_for = StateTest.expect_token('endfor')37switch_if = StateTest.expect_token('else', 'elif', 'endif')38end_of_if = StateTest.expect_token('endif')39end_of_filter = StateTest.expect_token('endfilter')40end_of_macro = StateTest.expect_token('endmacro')41end_of_call = StateTest.expect_token('endcall')42end_of_block_tag = StateTest.expect_token('endblock')43end_of_trans = StateTest.expect_token('endtrans')4445# this ends a tuple46tuple_edge_tokens = set(['rparen', 'block_end', 'variable_end', 'in',47 'recursive'])484950class Parser(object):51 """52 The template parser class.5354 Transforms sourcecode into an abstract syntax tree.55 """5657 def __init__(self, environment, source, filename=None):58 self.environment = environment59 if isinstance(source, str):60 source = source.decode(environment.template_charset, 'ignore')61 if isinstance(filename, unicode):62 filename = filename.encode('utf-8')63 self.source = source64 self.filename = filename65 self.closed = False6667 #: set for blocks in order to keep them unique68 self.blocks = set()6970 #: mapping of directives that require special treatment71 self.directives = {72 # "fake" directives that just trigger errors73 'raw': self.parse_raw_directive,74 'extends': self.parse_extends_directive,7576 # real directives77 'for': self.parse_for_loop,78 'if': self.parse_if_condition,79 'cycle': self.parse_cycle_directive,80 'call': self.parse_call_directive,81 'set': self.parse_set_directive,82 'filter': self.parse_filter_directive,83 'print': self.parse_print_directive,84 'macro': self.parse_macro_directive,85 'block': self.parse_block_directive,86 'include': self.parse_include_directive,87 'trans': self.parse_trans_directive88 }8990 #: set of directives that are only available in a certain91 #: context.92 self.context_directives = set([93 'elif', 'else', 'endblock', 'endfilter', 'endfor', 'endif',94 'endmacro', 'endraw', 'endtrans', 'pluralize'95 ])9697 #: get the `no_variable_block` flag98 self.no_variable_block = self.environment.lexer.no_variable_block99100 self.stream = environment.lexer.tokenize(source, filename)101102 def parse_raw_directive(self):103 """104 Handle fake raw directive. (real raw directives are handled by105 the lexer. But if there are arguments to raw or the end tag106 is missing the parser tries to resolve this directive. In that107 case present the user a useful error message.108 """109 if self.stream:110 raise TemplateSyntaxError('raw directive does not support '111 'any arguments.', self.stream.lineno,112 self.filename)113 raise TemplateSyntaxError('missing end tag for raw directive.',114 self.stream.lineno, self.filename)115116 def parse_extends_directive(self):117 """118 Handle the extends directive used for inheritance.119 """120 raise TemplateSyntaxError('mispositioned extends tag. extends must '121 'be the first tag of a template.',122 self.stream.lineno, self.filename)123124 def parse_for_loop(self):125 """126 Handle a for directive and return a ForLoop node127 """128 token = self.stream.expect('for')129 item = self.parse_tuple_expression(simplified=True)130 if not item.allows_assignments():131 raise TemplateSyntaxError('cannot assign to expression',132 token.lineno, self.filename)133134 self.stream.expect('in')135 seq = self.parse_tuple_expression()136 if self.stream.current.type == 'recursive':137 self.stream.next()138 recursive = True139 else:140 recursive = False141 self.stream.expect('block_end')142143 body = self.subparse(switch_for)144145 # do we have an else section?146 if self.stream.current.type == 'else':147 self.stream.next()148 self.stream.expect('block_end')149 else_ = self.subparse(end_of_for, True)150 else:151 self.stream.next()152 else_ = None153 self.stream.expect('block_end')154155 return nodes.ForLoop(item, seq, body, else_, recursive,156 token.lineno, self.filename)157158 def parse_if_condition(self):159 """160 Handle if/else blocks.161 """162 token = self.stream.expect('if')163 expr = self.parse_expression()164 self.stream.expect('block_end')165 tests = [(expr, self.subparse(switch_if))]166 else_ = None167168 # do we have an else section?169 while True:170 if self.stream.current.type == 'else':171 self.stream.next()172 self.stream.expect('block_end')173 else_ = self.subparse(end_of_if, True)174 elif self.stream.current.type == 'elif':175 self.stream.next()176 expr = self.parse_expression()177 self.stream.expect('block_end')178 tests.append((expr, self.subparse(switch_if)))179 continue180 else:181 self.stream.next()182 break183 self.stream.expect('block_end')184185 return nodes.IfCondition(tests, else_, token.lineno, self.filename)186187 def parse_cycle_directive(self):188 """189 Handle {% cycle foo, bar, baz %}.190 """191 token = self.stream.expect('cycle')192 expr = self.parse_tuple_expression()193 self.stream.expect('block_end')194 return nodes.Cycle(expr, token.lineno, self.filename)195196 def parse_set_directive(self):197 """198 Handle {% set foo = 'value of foo' %}.199 """200 token = self.stream.expect('set')201 name = self.stream.expect('name')202 self.test_name(name.value)203 self.stream.expect('assign')204 value = self.parse_expression()205 if self.stream.current.type == 'bang':206 self.stream.next()207 scope_local = False208 else:209 scope_local = True210 self.stream.expect('block_end')211 return nodes.Set(name.value, value, scope_local,212 token.lineno, self.filename)213214 def parse_filter_directive(self):215 """216 Handle {% filter foo|bar %} directives.217 """218 token = self.stream.expect('filter')219 filters = []220 while self.stream.current.type != 'block_end':221 if filters:222 self.stream.expect('pipe')223 token = self.stream.expect('name')224 args = []225 if self.stream.current.type == 'lparen':226 self.stream.next()227 while self.stream.current.type != 'rparen':228 if args:229 self.stream.expect('comma')230 args.append(self.parse_expression())231 self.stream.expect('rparen')232 filters.append((token.value, args))233 self.stream.expect('block_end')234 body = self.subparse(end_of_filter, True)235 self.stream.expect('block_end')236 return nodes.Filter(body, filters, token.lineno, self.filename)237238 def parse_print_directive(self):239 """240 Handle {% print foo %}.241 """242 token = self.stream.expect('print')243 expr = self.parse_tuple_expression()244 node = nodes.Print(expr, token.lineno, self.filename)245 self.stream.expect('block_end')246 return node247248 def parse_macro_directive(self):249 """250 Handle {% macro foo bar, baz %} as well as251 {% macro foo(bar, baz) %}.252 """253 token = self.stream.expect('macro')254 macro_name = self.stream.expect('name')255 self.test_name(macro_name.value)256 if self.stream.current.type == 'lparen':257 self.stream.next()258 needle_token = 'rparen'259 else:260 needle_token = 'block_end'261262 args = []263 while self.stream.current.type != needle_token:264 if args:265 self.stream.expect('comma')266 name = self.stream.expect('name').value267 self.test_name(name)268 if self.stream.current.type == 'assign':269 self.stream.next()270 default = self.parse_expression()271 else:272 default = None273 args.append((name, default))274275 self.stream.next()276 if needle_token == 'rparen':277 self.stream.expect('block_end')278279 body = self.subparse(end_of_macro, True)280 self.stream.expect('block_end')281282 return nodes.Macro(macro_name.value, args, body, token.lineno,283 self.filename)284285 def parse_call_directive(self):286 """287 Handle {% call foo() %}...{% endcall %}288 """289 token = self.stream.expect('call')290 expr = self.parse_call_expression()291 self.stream.expect('block_end')292 body = self.subparse(end_of_call, True)293 self.stream.expect('block_end')294 return nodes.Call(expr, body, token.lineno, self.filename)295296 def parse_block_directive(self):297 """298 Handle block directives used for inheritance.299 """300 token = self.stream.expect('block')301 name = self.stream.expect('name').value302303 # check if this block does not exist by now.304 if name in self.blocks:305 raise TemplateSyntaxError('block %r defined twice' %306 name, token.lineno,307 self.filename)308 self.blocks.add(name)309310 if self.stream.current.type != 'block_end':311 lineno = self.stream.lineno312 expr = self.parse_tuple_expression()313 node = nodes.Print(expr, lineno, self.filename)314 body = nodes.NodeList([node], lineno, self.filename)315 self.stream.expect('block_end')316 else:317 # otherwise parse the body and attach it to the block318 self.stream.expect('block_end')319 body = self.subparse(end_of_block_tag, True)320 self.stream.expect('block_end')321 return nodes.Block(name, body, token.lineno, self.filename)322323 def parse_include_directive(self):324 """325 Handle the include directive used for template inclusion.326 """327 token = self.stream.expect('include')328 template = self.stream.expect('string').value329 self.stream.expect('block_end')330 return nodes.Include(template, token.lineno, self.filename)331332 def parse_trans_directive(self):333 """334 Handle translatable sections.335 """336 trans_token = self.stream.expect('trans')337338 # string based translations {% trans "foo" %}339 if self.stream.current.type == 'string':340 text = self.stream.expect('string')341 self.stream.expect('block_end')342 return nodes.Trans(text.value, None, None, None,343 trans_token.lineno, self.filename)344345 # block based translations346 replacements = {}347 plural_var = None348349 while self.stream.current.type != 'block_end':350 if replacements:351 self.stream.expect('comma')352 name = self.stream.expect('name')353 if self.stream.current.type == 'assign':354 self.stream.next()355 value = self.parse_expression()356 else:357 value = nodes.NameExpression(name.value, name.lineno,358 self.filename)359 if name.value in replacements:360 raise TemplateSyntaxError('translation variable %r '361 'is defined twice' % name.value,362 name.lineno, self.filename)363 replacements[name.value] = value364 if plural_var is None:365 plural_var = name.value366 self.stream.expect('block_end')367368 def process_variable():369 var_name = self.stream.expect('name')370 if var_name.value not in replacements:371 raise TemplateSyntaxError('unregistered translation variable'372 " '%s'." % var_name.value,373 var_name.lineno, self.filename)374 buf.append('%%(%s)s' % var_name.value)375376 buf = singular = []377 plural = None378379 while True:380 token = self.stream.current381 if token.type == 'data':382 buf.append(token.value.replace('%', '%%'))383 self.stream.next()384 elif token.type == 'variable_begin':385 self.stream.next()386 process_variable()387 self.stream.expect('variable_end')388 elif token.type == 'block_begin':389 self.stream.next()390 if plural is None and self.stream.current.type == 'pluralize':391 self.stream.next()392 if self.stream.current.type == 'name':393 plural_var = self.stream.expect('name').value394 plural = buf = []395 elif self.stream.current.type == 'endtrans':396 self.stream.next()397 self.stream.expect('block_end')398 break399 else:400 if self.no_variable_block:401 process_variable()402 else:403 raise TemplateSyntaxError('blocks are not allowed '404 'in trans tags',405 self.stream.lineno,406 self.filename)407 self.stream.expect('block_end')408 else:409 assert False, 'something very strange happened'410411 singular = u''.join(singular)412 if plural is not None:413 plural = u''.join(plural)414 return nodes.Trans(singular, plural, plural_var, replacements,415 trans_token.lineno, self.filename)416417 def parse_expression(self):418 """419 Parse one expression from the stream.420 """421 return self.parse_conditional_expression()422423 def parse_subscribed_expression(self):424 """425 Like parse_expression but parses slices too. Because this426 parsing function requires a border the two tokens rbracket427 and comma mark the end of the expression in some situations.428 """429 lineno = self.stream.lineno430431 if self.stream.current.type == 'colon':432 self.stream.next()433 args = [None]434 else:435 node = self.parse_expression()436 if self.stream.current.type != 'colon':437 return node438 self.stream.next()439 args = [node]440441 if self.stream.current.type == 'colon':442 args.append(None)443 elif self.stream.current.type not in ('rbracket', 'comma'):444 args.append(self.parse_expression())445 else:446 args.append(None)447448 if self.stream.current.type == 'colon':449 self.stream.next()450 if self.stream.current.type not in ('rbracket', 'comma'):451 args.append(self.parse_expression())452 else:453 args.append(None)454 else:455 args.append(None)456457 return nodes.SliceExpression(*(args + [lineno, self.filename]))458459 def parse_conditional_expression(self):460 """461 Parse a conditional expression (foo if bar else baz)462 """463 lineno = self.stream.lineno464 expr1 = self.parse_or_expression()465 while self.stream.current.type == 'if':466 self.stream.next()467 expr2 = self.parse_or_expression()468 self.stream.expect('else')469 expr3 = self.parse_conditional_expression()470 expr1 = nodes.ConditionalExpression(expr2, expr1, expr3,471 lineno, self.filename)472 lineno = self.stream.lineno473 return expr1474475 def parse_or_expression(self):476 """477 Parse something like {{ foo or bar }}.478 """479 lineno = self.stream.lineno480 left = self.parse_and_expression()481 while self.stream.current.type == 'or':482 self.stream.next()483 right = self.parse_and_expression()484 left = nodes.OrExpression(left, right, lineno, self.filename)485 lineno = self.stream.lineno486 return left487488 def parse_and_expression(self):489 """490 Parse something like {{ foo and bar }}.491 """492 lineno = self.stream.lineno493 left = self.parse_compare_expression()494 while self.stream.current.type == 'and':495 self.stream.next()496 right = self.parse_compare_expression()497 left = nodes.AndExpression(left, right, lineno, self.filename)498 lineno = self.stream.lineno499 return left500501 def parse_compare_expression(self):502 """503 Parse something like {{ foo == bar }}.504 """505 known_operators = set(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq', 'in'])506 lineno = self.stream.lineno507 expr = self.parse_add_expression()508 ops = []509 while True:510 if self.stream.current.type in known_operators:511 op = self.stream.current.type512 self.stream.next()513 ops.append([op, self.parse_add_expression()])514 elif self.stream.current.type == 'not' and \515 self.stream.look().type == 'in':516 self.stream.skip(2)517 ops.append(['not in', self.parse_add_expression()])518 else:519 break520 if not ops:521 return expr522 return nodes.CompareExpression(expr, ops, lineno, self.filename)523524 def parse_add_expression(self):525 """526 Parse something like {{ foo + bar }}.527 """528 lineno = self.stream.lineno529 left = self.parse_sub_expression()530 while self.stream.current.type == 'add':531 self.stream.next()532 right = self.parse_sub_expression()533 left = nodes.AddExpression(left, right, lineno, self.filename)534 lineno = self.stream.lineno535 return left536537 def parse_sub_expression(self):538 """539 Parse something like {{ foo - bar }}.540 """541 lineno = self.stream.lineno542 left = self.parse_concat_expression()543 while self.stream.current.type == 'sub':544 self.stream.next()545 right = self.parse_concat_expression()546 left = nodes.SubExpression(left, right, lineno, self.filename)547 lineno = self.stream.lineno548 return left549550 def parse_concat_expression(self):551 """552 Parse something like {{ foo ~ bar }}.553 """554 lineno = self.stream.lineno555 args = [self.parse_mul_expression()]556 while self.stream.current.type == 'tilde':557 self.stream.next()558 args.append(self.parse_mul_expression())559 if len(args) == 1:560 return args[0]561 return nodes.ConcatExpression(args, lineno, self.filename)562563 def parse_mul_expression(self):564 """565 Parse something like {{ foo * bar }}.566 """567 lineno = self.stream.lineno568 left = self.parse_div_expression()569 while self.stream.current.type == 'mul':570 self.stream.next()571 right = self.parse_div_expression()572 left = nodes.MulExpression(left, right, lineno, self.filename)573 lineno = self.stream.lineno574 return left575576 def parse_div_expression(self):577 """578 Parse something like {{ foo / bar }}.579 """580 lineno = self.stream.lineno581 left = self.parse_floor_div_expression()582 while self.stream.current.type == 'div':583 self.stream.next()584 right = self.parse_floor_div_expression()585 left = nodes.DivExpression(left, right, lineno, self.filename)586 lineno = self.stream.lineno587 return left588589 def parse_floor_div_expression(self):590 """591 Parse something like {{ foo // bar }}.592 """593 lineno = self.stream.lineno594 left = self.parse_mod_expression()595 while self.stream.current.type == 'floordiv':596 self.stream.next()597 right = self.parse_mod_expression()598 left = nodes.FloorDivExpression(left, right, lineno, self.filename)599 lineno = self.stream.lineno600 return left601602 def parse_mod_expression(self):603 """604 Parse something like {{ foo % bar }}.605 """606 lineno = self.stream.lineno607 left = self.parse_pow_expression()608 while self.stream.current.type == 'mod':609 self.stream.next()610 right = self.parse_pow_expression()611 left = nodes.ModExpression(left, right, lineno, self.filename)612 lineno = self.stream.lineno613 return left614615 def parse_pow_expression(self):616 """617 Parse something like {{ foo ** bar }}.618 """619 lineno = self.stream.lineno620 left = self.parse_unary_expression()621 while self.stream.current.type == 'pow':622 self.stream.next()623 right = self.parse_unary_expression()624 left = nodes.PowExpression(left, right, lineno, self.filename)625 lineno = self.stream.lineno626 return left627628 def parse_unary_expression(self):629 """630 Parse all kinds of unary expressions.631 """632 if self.stream.current.type == 'not':633 return self.parse_not_expression()634 elif self.stream.current.type == 'sub':635 return self.parse_neg_expression()636 elif self.stream.current.type == 'add':637 return self.parse_pos_expression()638 return self.parse_primary_expression()639640 def parse_not_expression(self):641 """642 Parse something like {{ not foo }}.643 """644 token = self.stream.expect('not')645 node = self.parse_unary_expression()646 return nodes.NotExpression(node, token.lineno, self.filename)647648 def parse_neg_expression(self):649 """650 Parse something like {{ -foo }}.651 """652 token = self.stream.expect('sub')653 node = self.parse_unary_expression()654 return nodes.NegExpression(node, token.lineno, self.filename)655656 def parse_pos_expression(self):657 """658 Parse something like {{ +foo }}.659 """660 token = self.stream.expect('add')661 node = self.parse_unary_expression()662 return nodes.PosExpression(node, token.lineno, self.filename)663664 def parse_primary_expression(self, parse_postfix=True):665 """666 Parse a primary expression such as a name or literal.667 """668 current = self.stream.current669 if current.type == 'name':670 if current.value in ('true', 'false'):671 node = self.parse_bool_expression()672 elif current.value == 'none':673 node = self.parse_none_expression()674 elif current.value == 'undefined':675 node = self.parse_undefined_expression()676 elif current.value == '_':677 node = self.parse_gettext_call()678 else:679 node = self.parse_name_expression()680 elif current.type in ('integer', 'float'):681 node = self.parse_number_expression()682 elif current.type == 'string':683 node = self.parse_string_expression()684 elif current.type == 'regex':685 node = self.parse_regex_expression()686 elif current.type == 'lparen':687 node = self.parse_paren_expression()688 elif current.type == 'lbracket':689 node = self.parse_list_expression()690 elif current.type == 'lbrace':691 node = self.parse_dict_expression()692 elif current.type == 'at':693 node = self.parse_set_expression()694 else:695 raise TemplateSyntaxError("unexpected token '%s'" %696 self.stream.current,697 self.stream.current.lineno,698 self.filename)699 if parse_postfix:700 node = self.parse_postfix_expression(node)701 return node702703 def parse_tuple_expression(self, enforce=False, simplified=False):704 """705 Parse multiple expressions into a tuple. This can also return706 just one expression which is not a tuple. If you want to enforce707 a tuple, pass it enforce=True.708 """709 lineno = self.stream.lineno710 if simplified:711 parse = self.parse_primary_expression712 else:713 parse = self.parse_expression714 args = []715 is_tuple = False716 while True:717 if args:718 self.stream.expect('comma')719 if self.stream.current.type in tuple_edge_tokens:720 break721 args.append(parse())722 if self.stream.current.type == 'comma':723 is_tuple = True724 else:725 break726 if not is_tuple and args:727 if enforce:728 raise TemplateSyntaxError('tuple expected', lineno,729 self.filename)730 return args[0]731 return nodes.TupleExpression(args, lineno, self.filename)732733 def parse_bool_expression(self):734 """735 Parse a boolean literal.736 """737 token = self.stream.expect('name')738 if token.value == 'true':739 value = True740 elif token.value == 'false':741 value = False742 else:743 raise TemplateSyntaxError("expected boolean literal",744 token.lineno, self.filename)745 return nodes.ConstantExpression(value, token.lineno, self.filename)746747 def parse_none_expression(self):748 """749 Parse a none literal.750 """751 token = self.stream.expect('name', 'none')752 return nodes.ConstantExpression(None, token.lineno, self.filename)753754 def parse_undefined_expression(self):755 """756 Parse an undefined literal.757 """758 token = self.stream.expect('name', 'undefined')759 return nodes.UndefinedExpression(token.lineno, self.filename)760761 def parse_gettext_call(self):762 """763 parse {{ _('foo') }}.764 """765 # XXX: check if only one argument was passed and if766 # it is a string literal. Maybe that should become a special767 # expression anyway.768 token = self.stream.expect('name', '_')769 node = nodes.NameExpression(token.value, token.lineno, self.filename)770 return self.parse_call_expression(node)771772 def parse_name_expression(self):773 """774 Parse any name.775 """776 token = self.stream.expect('name')777 self.test_name(token.value)778 return nodes.NameExpression(token.value, token.lineno, self.filename)779780 def parse_number_expression(self):781 """782 Parse a number literal.783 """784 token = self.stream.current785 if token.type not in ('integer', 'float'):786 raise TemplateSyntaxError('integer or float literal expected',787 token.lineno, self.filename)788 self.stream.next()789 return nodes.ConstantExpression(token.value, token.lineno, self.filename)790791 def parse_string_expression(self):792 """793 Parse a string literal.794 """795 token = self.stream.expect('string')796 return nodes.ConstantExpression(token.value, token.lineno, self.filename)797798 def parse_regex_expression(self):799 """800 Parse a regex literal.801 """802 token = self.stream.expect('regex')803 return nodes.RegexExpression(token.value, token.lineno, self.filename)804805 def parse_paren_expression(self):806 """807 Parse a parenthized expression.808 """809 self.stream.expect('lparen')810 try:811 return self.parse_tuple_expression()812 finally:813 self.stream.expect('rparen')814815 def parse_list_expression(self):816 """817 Parse something like {{ [1, 2, "three"] }}818 """819 token = self.stream.expect('lbracket')820 items = []821 while self.stream.current.type != 'rbracket':822 if items:823 self.stream.expect('comma')824 if self.stream.current.type == 'rbracket':825 break826 items.append(self.parse_expression())827 self.stream.expect('rbracket')828829 return nodes.ListExpression(items, token.lineno, self.filename)830831 def parse_dict_expression(self):832 """833 Parse something like {{ {1: 2, 3: 4} }}834 """835 token = self.stream.expect('lbrace')836 items = []837 while self.stream.current.type != 'rbrace':838 if items:839 self.stream.expect('comma')840 if self.stream.current.type == 'rbrace':841 break842 key = self.parse_expression()843 self.stream.expect('colon')844 value = self.parse_expression()845 items.append((key, value))846 self.stream.expect('rbrace')847848 return nodes.DictExpression(items, token.lineno, self.filename)849850 def parse_set_expression(self):851 """852 Parse something like {{ @(1, 2, 3) }}.853 """854 token = self.stream.expect('at')855 self.stream.expect('lparen')856 items = []857 while self.stream.current.type != 'rparen':858 if items:859 self.stream.expect('comma')860 if self.stream.current.type == 'rparen':861 break862 items.append(self.parse_expression())863 self.stream.expect('rparen')864865 return nodes.SetExpression(items, token.lineno, self.filename)866867 def parse_postfix_expression(self, node):868 """869 Parse a postfix expression such as a filter statement or a870 function call.871 """872 while True:873 current = self.stream.current.type874 if current == 'dot' or current == 'lbracket':875 node = self.parse_subscript_expression(node)876 elif current == 'lparen':877 node = self.parse_call_expression(node)878 elif current == 'pipe':879 node = self.parse_filter_expression(node)880 elif current == 'is':881 node = self.parse_test_expression(node)882 else:883 break884 return node885886 def parse_subscript_expression(self, node):887 """888 Parse a subscript statement. Gets attributes and items from an889 object.890 """891 lineno = self.stream.lineno892 if self.stream.current.type == 'dot':893 self.stream.next()894 token = self.stream.current895 if token.type in ('name', 'integer'):896 arg = nodes.ConstantExpression(token.value, token.lineno,897 self.filename)898 else:899 raise TemplateSyntaxError('expected name or number',900 token.lineno, self.filename)901 self.stream.next()902 elif self.stream.current.type == 'lbracket':903 self.stream.next()904 args = []905 while self.stream.current.type != 'rbracket':906 if args:907 self.stream.expect('comma')908 args.append(self.parse_subscribed_expression())909 self.stream.expect('rbracket')910 if len(args) == 1:911 arg = args[0]912 else:913 arg = nodes.TupleExpression(args, lineno, self.filename)914 else:915 raise TemplateSyntaxError('expected subscript expression',916 self.lineno, self.filename)917 return nodes.SubscriptExpression(node, arg, lineno, self.filename)918919 def parse_call_expression(self, node=None):920 """921 Parse a call.922 """923 if node is None:924 node = self.parse_primary_expression(parse_postfix=False)925 token = self.stream.expect('lparen')926 args = []927 kwargs = []928 dyn_args = None929 dyn_kwargs = None930 require_comma = False931932 def ensure(expr):933 if not expr:934 raise TemplateSyntaxError('invalid syntax for function '935 'call expression', token.lineno,936 self.filename)937938 while self.stream.current.type != 'rparen':939 if require_comma:940 self.stream.expect('comma')941 # support for trailing comma942 if self.stream.current.type == 'rparen':943 break944 if self.stream.current.type == 'mul':945 ensure(dyn_args is None and dyn_kwargs is None)946 self.stream.next()947 dyn_args = self.parse_expression()948 elif self.stream.current.type == 'pow':949 ensure(dyn_kwargs is None)950 self.stream.next()951 dyn_kwargs = self.parse_expression()952 else:953 ensure(dyn_args is None and dyn_kwargs is None)954 if self.stream.current.type == 'name' and \955 self.stream.look().type == 'assign':956 key = self.stream.current.value957 self.stream.skip(2)958 kwargs.append((key, self.parse_expression()))959 else:960 ensure(not kwargs)961 args.append(self.parse_expression())962963 require_comma = True964 self.stream.expect('rparen')965966 return nodes.CallExpression(node, args, kwargs, dyn_args,967 dyn_kwargs, token.lineno,968 self.filename)969970 def parse_filter_expression(self, node):971 """972 Parse filter calls.973 """974 lineno = self.stream.lineno975 filters = []976 while self.stream.current.type == 'pipe':977 self.stream.next()978 token = self.stream.expect('name')979 args = []980 if self.stream.current.type == 'lparen':981 self.stream.next()982 while self.stream.current.type != 'rparen':983 if args:984 self.stream.expect('comma')985 args.append(self.parse_expression())986 self.stream.expect('rparen')987 filters.append((token.value, args))988 return nodes.FilterExpression(node, filters, lineno, self.filename)989990 def parse_test_expression(self, node):991 """992 Parse test calls.993 """994 token = self.stream.expect('is')995 if self.stream.current.type == 'not':996 self.stream.next()997 negated = True998 else:999 negated = False1000 name = self.stream.expect('name').value1001 args = []1002 if self.stream.current.type == 'lparen':1003 self.stream.next()1004 while self.stream.current.type != 'rparen':1005 if args:1006 self.stream.expect('comma')1007 args.append(self.parse_expression())1008 self.stream.expect('rparen')1009 elif self.stream.current.type in ('name', 'string', 'integer',1010 'float', 'lparen', 'lbracket',1011 'lbrace', 'regex'):1012 args.append(self.parse_expression())1013 node = nodes.TestExpression(node, name, args, token.lineno,1014 self.filename)1015 if negated:1016 node = nodes.NotExpression(node, token.lineno, self.filename)1017 return node10181019 def test_name(self, name):1020 """1021 Test if a name is not a special constant1022 """1023 if name in ('true', 'false', 'none', 'undefined', '_'):1024 raise TemplateSyntaxError('expected name not special constant',1025 self.stream.lineno, self.filename)10261027 def subparse(self, test, drop_needle=False):1028 """1029 Helper function used to parse the sourcecode until the test1030 function which is passed a tuple in the form (lineno, token, data)1031 returns True. In that case the current token is pushed back to1032 the stream and the generator ends.10331034 The test function is only called for the first token after a1035 block tag. Variable tags are *not* aliases for {% print %} in1036 that case.10371038 If drop_needle is True the needle_token is removed from the1039 stream.1040 """1041 if self.closed:1042 raise RuntimeError('parser is closed')1043 result = []1044 buffer = []1045 next = self.stream.next1046 lineno = self.stream.lineno10471048 def assemble_list():1049 push_buffer()1050 return nodes.NodeList(result, lineno, self.filename)10511052 def push_variable():1053 buffer.append((True, self.parse_tuple_expression()))10541055 def push_data():1056 buffer.append((False, self.stream.expect('data')))10571058 def push_buffer():1059 if not buffer:1060 return1061 template = []1062 variables = []1063 for is_var, data in buffer:1064 if is_var:1065 template.append('%s')1066 variables.append(data)1067 else:1068 template.append(data.value.replace('%', '%%'))1069 result.append(nodes.Text(u''.join(template), variables,1070 buffer[0][1].lineno, self.filename))1071 del buffer[:]10721073 def push_node(node):1074 push_buffer()1075 result.append(node)10761077 while self.stream:1078 token_type = self.stream.current.type1079 if token_type == 'variable_begin':1080 next()1081 push_variable()1082 self.stream.expect('variable_end')1083 elif token_type == 'raw_begin':1084 next()1085 push_data()1086 self.stream.expect('raw_end')1087 elif token_type == 'block_begin':1088 next()1089 if test is not None and test(self.stream.current):1090 if drop_needle:1091 next()1092 return assemble_list()1093 handler = self.directives.get(self.stream.current.type)1094 if handler is None:1095 if self.no_variable_block:1096 push_variable()1097 self.stream.expect('block_end')1098 elif self.stream.current.type in self.context_directives:1099 raise TemplateSyntaxError('unexpected directive %r.' %1100 self.stream.current.type,1101 lineno, self.filename)1102 else:1103 name = self.stream.current.value1104 raise TemplateSyntaxError('unknown directive %r.' %1105 name, lineno, self.filename)1106 else:1107 node = handler()1108 if node is not None:1109 push_node(node)1110 elif token_type == 'data':1111 push_data()11121113 # this should be unreachable code1114 else:1115 assert False, "unexpected token %r" % self.stream.current11161117 if test is not None:1118 msg = isinstance(test, StateTest) and ': ' + test.msg or ''1119 raise TemplateSyntaxError('unexpected end of stream' + msg,1120 self.stream.lineno, self.filename)11211122 return assemble_list()11231124 def sanitize_tree(self, body, extends):1125 self._sanitize_tree([body], [body], extends, body)1126 return body11271128 def _sanitize_tree(self, nodelist, stack, extends, body):1129 """1130 This is not a closure because python leaks memory if it is. It's used1131 by `parse()` to make sure blocks do not trigger unexpected behavior.1132 """1133 for node in nodelist:1134 if extends is not None and \1135 node.__class__ is nodes.Block and \1136 stack[-1] is not body:1137 for n in stack:1138 if n.__class__ is nodes.Block:1139 break1140 else:1141 raise TemplateSyntaxError('misplaced block %r, '1142 'blocks in child '1143 'templates must be '1144 'either top level or '1145 'located in a block '1146 'tag.' % node.name,1147 node.lineno,1148 self.filename)1149 stack.append(node)1150 self._sanitize_tree(node.get_child_nodes(), stack, extends, body)1151 stack.pop()11521153 def parse(self):1154 """1155 Parse the template and return a Template node. This also does some1156 post processing sanitizing and parses for an extends tag.1157 """1158 if self.closed:1159 raise RuntimeError('parser is closed')11601161 try:1162 # get the leading whitespace, if we are not in a child1163 # template we push that back to the stream later.1164 leading_whitespace = self.stream.read_whitespace()11651166 # parse an optional extends which *must* be the first node1167 # of a template.1168 if self.stream.current.type == 'block_begin' and \1169 self.stream.look().type == 'extends':1170 self.stream.skip(2)1171 extends = self.stream.expect('string').value1172 self.stream.expect('block_end')1173 else:1174 extends = None1175 if leading_whitespace:1176 self.stream.shift(leading_whitespace)11771178 body = self.sanitize_tree(self.subparse(None), extends)1179 return nodes.Template(extends, body, 1, self.filename)1180 finally:1181 self.close()11821183 def close(self):1184 """Clean up soon."""1185 self.closed = True1186 self.stream = self.directives = self.stream = self.blocks = \1187 self.environment = None
deleted:jinja/plugin.py-166 removed
1# -*- coding: utf-8 -*-2"""3 jinja.plugin4 ~~~~~~~~~~~~56 Support for the `GeneralTemplateInterface`__ and the Buffet interface.78 Do not use this module on your own. We don't recommend those interfaces!9 If you are able to, you should really use Jinja without those abstraction10 layers.1112 __ http://trac.pocoo.org/wiki/GeneralTemplateInterface1314 :copyright: 2007 by Armin Ronacher.15 :license: BSD, see LICENSE for more details.16"""17from warnings import warn18from jinja.environment import Environment19from jinja.loaders import FunctionLoader, FileSystemLoader, PackageLoader20from jinja.exceptions import TemplateNotFound212223class BuffetPlugin(object):24 """25 Implements the Jinja buffet plugin. Well. It works for pylons and should26 work for TurboGears too if their plugin system would work.27 """2829 def __init__(self, extra_vars_func=None, options=None):30 if 'jinja.environment' in options:31 self.env = options['jinja.environment']32 else:33 opt = {}34 for key, value in options.iteritems():35 if key.startswith('jinja.') and key != 'jinja.extension':36 opt[key[6:]] = value37 loader_func = opt.pop('loader_func', None)38 getmtime_func = opt.pop('getmtime_func', None)39 use_memcache = opt.pop('use_memcache', False)40 memcache_size = opt.pop('memcache_size', 40)41 cache_folder = opt.pop('cache_folder', None)42 auto_reload = opt.pop('auto_reload', True)43 if 'searchpath' in opt:44 opt['loader'] = FileSystemLoader(opt.pop('searchpath'),45 use_memcache, memcache_size,46 cache_folder, auto_reload)47 elif 'package' in opt:48 opt['loader'] = PackageLoader(opt.pop('package'),49 opt.pop('package_path', ''),50 use_memcache, memcache_size,51 cache_folder, auto_reload)52 elif loader_func is not None:53 opt['loader'] = FunctionLoader(loader_func, getmtime_func,54 use_memcache, memcache_size,55 cache_folder, auto_reload)56 self.env = Environment(**opt)5758 self.extra_vars_func = extra_vars_func59 self.extension = options.pop('jinja.extension', 'html')6061 def load_template(self, templatename, template_string=None):62 if template_string is not None:63 return self.env.from_string(template_string)64 if templatename.startswith('!'):65 jinja_name = templatename[1:]66 else:67 jinja_name = templatename.replace('.', '/') + '.' + self.extension68 return self.env.get_template(jinja_name)6970 def render(self, info, format='html', fragment=False, template=None):71 if isinstance(template, basestring):72 template = self.load_template(template)73 if self.extra_vars_func:74 info.update(self.extra_vars_func())75 return template.render(info)767778def jinja_plugin_factory(options):79 """80 Basic implementation of the `GeneralTemplateInterface`.8182 Supports ``loader_func`` and ``getmtime_func``, as well as83 string and file loading but ignores ``mode`` since it's a84 text based template engine.8586 All options passed to this function are forwarded to the87 jinja environment. Exceptions are the following keys:8889 =================== =================================================90 ``environment`` If this is provided it must be the only91 configuration value and it's used as jinja92 environment.93 ``searchpath`` If provided a new file system loader with this94 search path is instanciated.95 ``package`` Name of the python package containing the96 templates. If this and ``package_path`` is97 defined a `PackageLoader` is used.98 ``package_path`` Path to the templates inside of a package.99 ``loader_func`` Function that takes the name of the template to100 load. If it returns a string or unicode object101 it's used to load a template. If the return102 value is None it's considered missing.103 ``getmtime_func`` Function used to check if templates requires104 reloading. Has to return the UNIX timestamp of105 the last template change or 0 if this template106 does not exist or requires updates at any cost.107 ``use_memcache`` Set this to ``True`` to enable memory caching.108 This is usually a good idea in production mode,109 but disable it during development since it won't110 reload template changes automatically.111 This only works in persistent environments like112 FastCGI.113 ``memcache_size`` Number of template instance you want to cache.114 Defaults to ``40``.115 ``cache_folder`` Set this to an existing directory to enable116 caching of templates on the file system. Note117 that this only affects templates transformed118 into python code. Default is ``None`` which means119 that caching is disabled.120 ``auto_reload`` Set this to `False` for a slightly better121 performance. In that case of `getmtime_func`122 not being provided this won't have an effect.123 =================== =================================================124 """125 warn(DeprecationWarning('general plugin interface implementation '126 'deprecated because not an accepted '127 'standard.'))128129 if 'environment' in options:130 env = options['environment']131 if not len(options) == 1:132 raise TypeError('if environment provided no other '133 'arguments are allowed')134 else:135 loader_func = options.pop('loader_func', None)136 getmtime_func = options.pop('getmtime_func', None)137 use_memcache = options.pop('use_memcache', False)138 memcache_size = options.pop('memcache_size', 40)139 cache_folder = options.pop('cache_folder', None)140 auto_reload = options.pop('auto_reload', True)141 if 'searchpath' in options:142 options['loader'] = FileSystemLoader(options.pop('searchpath'),143 use_memcache, memcache_size,144 cache_folder, auto_reload)145 elif 'package' in options:146 options['loader'] = PackageLoader(options.pop('package'),147 options.pop('package_path', ''),148 use_memcache, memcache_size,149 cache_folder, auto_reload)150 elif loader_func is not None:151 options['loader'] = FunctionLoader(loader_func, getmtime_func,152 use_memcache, memcache_size,153 cache_folder, auto_reload)154 env = Environment(**options)155156 def render_function(template, values, options):157 if options.get('is_string'):158 tmpl = env.from_string(template)159 else:160 try:161 tmpl = env.get_template(template)162 except TemplateNotFound:163 return164 return tmpl.render(**values)165166 return render_function
deleted:jinja/tests.py-143 removed
1# -*- coding: utf-8 -*-2"""3 jinja.tests4 ~~~~~~~~~~~56 Jinja test functions. Used with the "is" operator.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re121314number_re = re.compile(r'^-?\d+(\.\d+)?$')15regex_type = type(number_re)161718def test_odd():19 """20 Return true if the variable is odd.21 """22 return lambda e, c, v: v % 2 == 1232425def test_even():26 """27 Return true of the variable is even.28 """29 return lambda e, c, v: v % 2 == 0303132def test_defined():33 """34 Return true if the variable is defined:3536 .. sourcecode:: jinja3738 {% if variable is defined %}39 value of variable: {{ variable }}40 {% else %}41 variable is not defined42 {% endif %}4344 See also the ``default`` filter.45 """46 return lambda e, c, v: v is not e.undefined_singleton474849def test_lower():50 """51 Return true if the variable is lowercase.52 """53 return lambda e, c, v: isinstance(v, basestring) and v.islower()545556def test_upper():57 """58 Return true if the variable is uppercase.59 """60 return lambda e, c, v: isinstance(v, basestring) and v.isupper()616263def test_numeric():64 """65 Return true if the variable is numeric.66 """67 return lambda e, c, v: isinstance(v, (int, long, float)) or (68 isinstance(v, basestring) and69 number_re.match(v) is not None)707172def test_sequence():73 """74 Return true if the variable is a sequence. Sequences are variables75 that are iterable.76 """77 def wrapped(environment, context, value):78 try:79 len(value)80 value.__getitem__81 except:82 return False83 return True84 return wrapped858687def test_matching(regex):88 r"""89 Test if the variable matches the regular expression given. Note that90 you have to escape special chars using *two* backslashes, these are91 *not* raw strings.9293 .. sourcecode:: jinja9495 {% if var is matching @/^\d+$/ %}96 var looks like a number97 {% else %}98 var doesn't really look like a number99 {% endif %}100 """101 def wrapped(environment, context, value):102 if type(regex) is regex_type:103 regex_ = regex104 else:105 if environment.disable_regexps:106 raise RuntimeError('regular expressions disabled.')107 if isinstance(regex, unicode):108 regex_ = re.compile(regex, re.U)109 elif isinstance(regex, str):110 regex_ = re.compile(regex)111 else:112 return False113 return regex_.search(value) is not None114 return wrapped115116117def test_sameas(other):118 """119 Check if an object points to the same memory address than another120 object:121122 .. sourcecode:: jinja123124 {% if foo.attribute is sameas(false) %}125 the foo attribute really is the `False` singleton126 {% endif %}127128 *New in Jinja 1.2*129 """130 return lambda e, c, v: v is other131132133TESTS = {134 'odd': test_odd,135 'even': test_even,136 'defined': test_defined,137 'lower': test_lower,138 'upper': test_upper,139 'numeric': test_numeric,140 'sequence': test_sequence,141 'matching': test_matching,142 'sameas': test_sameas143}
deleted:jinja/utils.py-645 removed
1# -*- coding: utf-8 -*-2"""3 jinja.utils4 ~~~~~~~~~~~56 Utility functions.78 **license information**: some of the regular expressions and9 the ``urlize`` function were taken from the django framework.1011 :copyright: 2007 by Armin Ronacher, Lawrence Journal-World.12 :license: BSD, see LICENSE for more details.13"""14import re15import sys16import string17from types import MethodType, FunctionType18from jinja import nodes19from jinja.exceptions import SecurityException, TemplateNotFound20from jinja.datastructure import TemplateData2122# the python2.4 version of deque is missing the remove method23# because a for loop with a lookup for the missing value written24# in python is slower we just use deque if we have python2.5 or higher25try:26 from collections import deque27 deque.remove28except (ImportError, AttributeError):29 class deque(list):30 """31 Minimal subclass of list that provides the deque32 interface used by the native `BaseContext` and the33 `CacheDict`34 """35 def appendleft(self, item):36 list.insert(self, 0, item)37 def popleft(self):38 return list.pop(self, 0)39 def clear(self):40 del self[:]4142# support for a working reversed() in 2.343try:44 reversed = reversed45except NameError:46 def reversed(iterable):47 if hasattr(iterable, '__reversed__'):48 return iterable.__reversed__()49 try:50 return iter(iterable[::-1])51 except TypeError:52 return iter(tuple(iterable)[::-1])5354# set support for python 2.355try:56 set = set57except NameError:58 from sets import Set as set5960# sorted support (just a simplified version)61try:62 sorted = sorted63except NameError:64 _cmp = cmp65 def sorted(seq, cmp=None, key=None, reverse=False):66 rv = list(seq)67 if key is not None:68 cmp = lambda a, b: _cmp(key(a), key(b))69 rv.sort(cmp)70 if reverse:71 rv.reverse()72 return rv7374# group by support75try:76 from itertools import groupby77except ImportError:78 class groupby(object):7980 def __init__(self, iterable, key=lambda x: x):81 self.keyfunc = key82 self.it = iter(iterable)83 self.tgtkey = self.currkey = self.currvalue = xrange(0)8485 def __iter__(self):86 return self8788 def next(self):89 while self.currkey == self.tgtkey:90 self.currvalue = self.it.next()91 self.currkey = self.keyfunc(self.currvalue)92 self.tgtkey = self.currkey93 return (self.currkey, self._grouper(self.tgtkey))9495 def _grouper(self, tgtkey):96 while self.currkey == tgtkey:97 yield self.currvalue98 self.currvalue = self.it.next()99 self.currkey = self.keyfunc(self.currvalue)100101#: function types102callable_types = (FunctionType, MethodType)103104#: number of maximal range items105MAX_RANGE = 1000000106107_word_split_re = re.compile(r'(\s+)')108109_punctuation_re = re.compile(110 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (111 '|'.join([re.escape(p) for p in ('(', '<', '&lt;')]),112 '|'.join([re.escape(p) for p in ('.', ',', ')', '>', '\n', '&gt;')])113 )114)115116_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')117118#: used by from_string as cache119_from_string_env = None120121122def escape(s, quote=None):123 """124 SGML/XML escape an unicode object.125 """126 s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")127 if not quote:128 return s129 return s.replace('"', "&quot;")130131132def urlize(text, trim_url_limit=None, nofollow=False):133 """134 Converts any URLs in text into clickable links. Works on http://,135 https:// and www. links. Links can have trailing punctuation (periods,136 commas, close-parens) and leading punctuation (opening parens) and137 it'll still do the right thing.138139 If trim_url_limit is not None, the URLs in link text will be limited140 to trim_url_limit characters.141142 If nofollow is True, the URLs in link text will get a rel="nofollow"143 attribute.144 """145 trim_url = lambda x, limit=trim_url_limit: limit is not None \146 and (x[:limit] + (len(x) >=limit and '...'147 or '')) or x148 words = _word_split_re.split(text)149 nofollow_attr = nofollow and ' rel="nofollow"' or ''150 for i, word in enumerate(words):151 match = _punctuation_re.match(word)152 if match:153 lead, middle, trail = match.groups()154 if middle.startswith('www.') or (155 '@' not in middle and156 not middle.startswith('http://') and157 len(middle) > 0 and158 middle[0] in string.letters + string.digits and (159 middle.endswith('.org') or160 middle.endswith('.net') or161 middle.endswith('.com')162 )):163 middle = '<a href="http://%s"%s>%s</a>' % (middle,164 nofollow_attr, trim_url(middle))165 if middle.startswith('http://') or \166 middle.startswith('https://'):167 middle = '<a href="%s"%s>%s</a>' % (middle,168 nofollow_attr, trim_url(middle))169 if '@' in middle and not middle.startswith('www.') and \170 not ':' in middle and _simple_email_re.match(middle):171 middle = '<a href="mailto:%s">%s</a>' % (middle, middle)172 if lead + middle + trail != word:173 words[i] = lead + middle + trail174 return u''.join(words)175176177def from_string(source):178 """179 Create a template from the template source.180 """181 global _from_string_env182 if _from_string_env is None:183 from jinja.environment import Environment184 _from_string_env = Environment()185 return _from_string_env.from_string(source)186187188#: minor speedup189_getattr = getattr190191def get_attribute(obj, name):192 """193 Return the attribute from name. Raise either `AttributeError`194 or `SecurityException` if something goes wrong.195 """196 if not isinstance(name, basestring):197 raise AttributeError(name)198 if name[:2] == name[-2:] == '__':199 raise SecurityException('not allowed to access internal attributes')200 if getattr(obj, '__class__', None) in callable_types and \201 name.startswith('func_') or name.startswith('im_'):202 raise SecurityException('not allowed to access function attributes')203204 r = _getattr(obj, 'jinja_allowed_attributes', None)205 if r is not None and name not in r:206 raise SecurityException('disallowed attribute accessed')207208 # attribute lookups convert unicode strings to ascii bytestrings.209 # this process could raise an UnicodeEncodeError.210 try:211 return _getattr(obj, name)212 except UnicodeError:213 raise AttributeError(name)214215216def safe_range(start, stop=None, step=None):217 """218 "Safe" form of range that does not generate too large lists.219 """220 if step is None:221 step = 1222 if stop is None:223 r = xrange(0, start, step)224 else:225 r = xrange(start, stop, step)226 if len(r) > MAX_RANGE:227 def limit():228 i = 0229 for item in r:230 i += 1231 yield item232 if i >= MAX_RANGE:233 break234 return list(limit())235 return list(r)236237238def generate_lorem_ipsum(n=5, html=True, min=20, max=100):239 """240 Generate some lorem impsum for the template.241 """242 from jinja.constants import LOREM_IPSUM_WORDS243 from random import choice, random, randrange244 words = LOREM_IPSUM_WORDS.split()245 result = []246247 for _ in xrange(n):248 next_capitalized = True249 last_comma = last_fullstop = 0250 word = None251 last = None252 p = []253254 # each paragraph contains out of 20 to 100 words.255 for idx, _ in enumerate(xrange(randrange(min, max))):256 while True:257 word = choice(words)258 if word != last:259 last = word260 break261 if next_capitalized:262 word = word.capitalize()263 next_capitalized = False264 # add commas265 if idx - randrange(3, 8) > last_comma:266 last_comma = idx267 last_fullstop += 2268 word += ','269 # add end of sentences270 if idx - randrange(10, 20) > last_fullstop:271 last_comma = last_fullstop = idx272 word += '.'273 next_capitalized = True274 p.append(word)275276 # ensure that the paragraph ends with a dot.277 p = u' '.join(p)278 if p.endswith(','):279 p = p[:-1] + '.'280 elif not p.endswith('.'):281 p += '.'282 result.append(p)283284 if not html:285 return u'\n\n'.join(result)286 return u'\n'.join([u'<p>%s</p>' % escape(x) for x in result])287288289def watch_changes(env, context, iterable, *attributes):290 """291 Wise replacement for ``{% ifchanged %}``.292 """293 # find the attributes to watch294 if attributes:295 tests = []296 tmp = []297 for attribute in attributes:298 if isinstance(attribute, (str, unicode, int, long, bool)):299 tmp.append(attribute)300 else:301 tests.append(tuple(attribute))302 if tmp:303 tests.append(tuple(attribute))304 last = tuple([object() for x in tests])305 # or no attributes if we watch the object itself306 else:307 tests = None308 last = object()309310 # iterate trough it and keep check the attributes or values311 for item in iterable:312 if tests is None:313 cur = item314 else:315 cur = tuple([env.get_attributes(item, x) for x in tests])316 if cur != last:317 changed = True318 last = cur319 else:320 changed = False321 yield changed, item322watch_changes.jinja_context_callable = True323324325def render_included(env, context, template_name):326 """327 Works like djangos {% include %} tag. It doesn't include the328 template but load it independently and renders it to a string.329 """330 #XXX: ignores parent completely!331 tmpl = env.get_template(template_name)332 return tmpl.render(context.to_dict())333render_included.jinja_context_callable = True334335336# python2.4 and lower has a bug regarding joining of broken generators.337# because of the runtime debugging system we have to keep track of the338# number of frames to skip. that's what RUNTIME_EXCEPTION_OFFSET is for.339try:340 _test_singleton = object()341 def _test_gen_bug():342 raise TypeError(_test_singleton)343 yield None344 ''.join(_test_gen_bug())345except TypeError, e:346 if e.args and e.args[0] is _test_singleton:347 capture_generator = u''.join348 RUNTIME_EXCEPTION_OFFSET = 1349 else:350 capture_generator = lambda gen: u''.join(tuple(gen))351 RUNTIME_EXCEPTION_OFFSET = 2352del _test_singleton, _test_gen_bug353354355def pformat(obj, verbose=False):356 """357 Prettyprint an object. Either use the `pretty` library or the358 builtin `pprint`.359 """360 try:361 from pretty import pretty362 return pretty(obj, verbose=verbose)363 except ImportError:364 from pprint import pformat365 return pformat(obj)366367368def buffereater(f, template_data=False):369 """370 Used by the python translator to capture output of substreams.371 (macros, filter sections etc)372 """373 def wrapped(*a, **kw):374 __traceback_hide__ = True375 rv = capture_generator(f(*a, **kw))376 if template_data:377 rv = TemplateData(rv)378 return rv379 return wrapped380381382def empty_block(context):383 """384 An empty callable that just returns an empty decorator.385 Used to represent empty blocks.386 """387 if 0: yield None388389390def collect_translations(ast):391 """392 Collect all translatable strings for the given ast. The393 return value is a list of tuples in the form ``(lineno, singular,394 plural)``. If a translation doesn't require a plural form the395 third item is `None`.396 """397 todo = [ast]398 result = []399 while todo:400 node = todo.pop()401 if node.__class__ is nodes.Trans:402 result.append((node.lineno, node.singular, node.plural))403 elif node.__class__ is nodes.CallExpression and \404 node.node.__class__ is nodes.NameExpression and \405 node.node.name == '_':406 if len(node.args) == 1 and not node.kwargs and not node.dyn_args \407 and not node.dyn_kwargs and \408 node.args[0].__class__ is nodes.ConstantExpression:409 result.append((node.lineno, node.args[0].value, None))410 todo.extend(node.get_child_nodes())411 result.sort(lambda a, b: cmp(a[0], b[0]))412 return result413414415class DebugHelper(object):416 """417 Debugging Helper. Available in the template as "debug".418 """419 jinja_context_callable = True420 jinja_allowed_attributes = ['filters']421422 def __init__(self):423 raise TypeError('cannot create %r instances' %424 self.__class__.__name__)425426 def __call__(self, env, context):427 """Print a nice representation of the context."""428 return pformat(context.to_dict(), verbose=True)429430 def filters(self, env, context, builtins=True):431 """List the filters."""432 from inspect import getdoc433 strip = set()434 if not builtins:435 from jinja.defaults import DEFAULT_FILTERS436 strip = set(DEFAULT_FILTERS.values())437 filters = env.filters.items()438 filters.sort(lambda a, b: cmp(a[0].lower(), b[0].lower()))439 result = []440 for name, f in filters:441 if f in strip:442 continue443 doc = '\n'.join([' ' + x for x in (getdoc(f) or '').splitlines()])444 result.append('`%s`\n\n%s' % (name, doc))445 return '\n\n'.join(result)446 filters.jinja_context_callable = True447448 def tests(self, env, context, builtins=True):449 """List the tests."""450 from inspect import getdoc451 strip = set()452 if not builtins:453 from jinja.defaults import DEFAULT_TESTS454 strip = set(DEFAULT_TESTS.values())455 tests = env.tests.items()456 tests.sort(lambda a, b: cmp(a[0].lower(), b[0].lower()))457 result = []458 for name, f in tests:459 if f in strip:460 continue461 doc = '\n'.join([' ' + x for x in (getdoc(f) or '').splitlines()])462 result.append('`%s`\n\n%s' % (name, doc))463 return '\n\n'.join(result)464 tests.jinja_context_callable = True465466 def __str__(self):467 print 'use debug() for debugging the context'468469470#: the singleton instance of `DebugHelper`471debug_helper = object.__new__(DebugHelper)472473474class CacheDict(object):475 """476 A dict like object that stores a limited number of items and forgets477 about the least recently used items::478479 >>> cache = CacheDict(3)480 >>> cache['A'] = 0481 >>> cache['B'] = 1482 >>> cache['C'] = 2483 >>> len(cache)484 3485486 If we now access 'A' again it has a higher priority than B::487488 >>> cache['A']489 0490491 If we add a new item 'D' now 'B' will disappear::492493 >>> cache['D'] = 3494 >>> len(cache)495 3496 >>> 'B' in cache497 False498499 If you iterate over the object the most recently used item will be500 yielded First::501502 >>> for item in cache:503 ... print item504 D505 A506 C507508 If you want to iterate the other way round use ``reverse(cache)``.509510 Implementation note: This is not a nice way to solve that problem but511 for smaller capacities it's faster than a linked list.512 Perfect for template environments where you don't expect too many513 different keys.514 """515516 def __init__(self, capacity):517 self.capacity = capacity518 self._mapping = {}519 self._queue = deque()520521 # alias all queue methods for faster lookup522 self._popleft = self._queue.popleft523 self._pop = self._queue.pop524 self._remove = self._queue.remove525 self._append = self._queue.append526527 def copy(self):528 """529 Return an shallow copy of the instance.530 """531 rv = CacheDict(self.capacity)532 rv._mapping.update(self._mapping)533 rv._queue = self._queue[:]534 return rv535536 def get(self, key, default=None):537 """538 Return an item from the cache dict or `default`539 """540 if key in self:541 return self[key]542 return default543544 def setdefault(self, key, default=None):545 """546 Set `default` if the key is not in the cache otherwise547 leave unchanged. Return the value of this key.548 """549 if key in self:550 return self[key]551 self[key] = default552 return default553554 def clear(self):555 """556 Clear the cache dict.557 """558 self._mapping.clear()559 self._queue.clear()560561 def __contains__(self, key):562 """563 Check if a key exists in this cache dict.564 """565 return key in self._mapping566567 def __len__(self):568 """569 Return the current size of the cache dict.570 """571 return len(self._mapping)572573 def __repr__(self):574 return '<%s %r>' % (575 self.__class__.__name__,576 self._mapping577 )578579 def __getitem__(self, key):580 """581 Get an item from the cache dict. Moves the item up so that582 it has the highest priority then.583584 Raise an `KeyError` if it does not exist.585 """586 rv = self._mapping[key]587 if self._queue[-1] != key:588 self._remove(key)589 self._append(key)590 return rv591592 def __setitem__(self, key, value):593 """594 Sets the value for an item. Moves the item up so that it595 has the highest priority then.596 """597 if key in self._mapping:598 self._remove(key)599 elif len(self._mapping) == self.capacity:600 del self._mapping[self._popleft()]601 self._append(key)602 self._mapping[key] = value603604 def __delitem__(self, key):605 """606 Remove an item from the cache dict.607 Raise an `KeyError` if it does not exist.608 """609 del self._mapping[key]610 self._remove(key)611612 def __iter__(self):613 """614 Iterate over all values in the cache dict, ordered by615 the most recent usage.616 """617 return reversed(self._queue)618619 def __reversed__(self):620 """621 Iterate over the values in the cache dict, oldest items622 coming first.623 """624 return iter(self._queue)625626 __copy__ = copy627628 def __deepcopy__(self):629 """630 Return a deep copy of the cache dict.631 """632 from copy import deepcopy633 rv = CacheDict(self.capacity)634 rv._mapping = deepcopy(self._mapping)635 rv._queue = deepcopy(self._queue)636 return rv637638639NAMESPACE = {640 'range': safe_range,641 'debug': debug_helper,642 'lipsum': generate_lorem_ipsum,643 'watchchanges': watch_changes,644 'rendertemplate': render_included645}
added:jinja2/contrib/__init__.py+11 added
1# -*- coding: utf-8 -*-2"""3 jinja.contrib4 ~~~~~~~~~~~~~56 This module collections various third-party helper functions and classes7 that are useful for frameworks etc.89 :copyright: 2007 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""
added:jinja2/contrib/_djangosupport.py+209 added
1# -*- coding: utf-8 -*-2"""3 jinja.contrib._djangosupport4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 Django suport layer. This module is a metamodule, do never import it7 directly or access any of the functions defined here.89 The public interface is `jinja.contrib.djangosupport` and10 `django.contrib.jinja`. See the docstring of `jinja.contrib.djangosupport`11 for more details.1213 :copyright: 2007-2008 by Armin Ronacher, Bryan McLemore, David Cramer.14 :license: BSD, see LICENSE for more details.15"""16import sys17import warnings18import new19from django.conf import settings20from django.template.context import get_standard_processors21from django.http import HttpResponse22from django import contrib2324from jinja import Environment, FileSystemLoader, ChoiceLoader25from jinja.loaders import MemcachedFileSystemLoader262728exported = ['render_to_response', 'render_to_string', 'convert_django_filter']293031#: used environment32env = None333435#: default filters36DEFAULT_FILTERS = (37 'django.template.defaultfilters.date',38 'django.template.defaultfilters.timesince',39 'django.template.defaultfilters.linebreaks',40 'django.contrib.humanize.templatetags.humanize.intcomma'41)4243def configure(convert_filters=DEFAULT_FILTERS, loader=None, **options):44 """45 Initialize the system.46 """47 global env4849 if env:50 warnings.warn("Jinja already initialized.")51 return5253 # setup environment54 if loader is None:55 loaders = tuple(FileSystemLoader(l) for l in settings.TEMPLATE_DIRS)56 if not loaders:57 loader = None58 elif len(loaders) == 1:59 loader = loaders[0]60 else:61 loader = ChoiceLoader(loaders)62 env = Environment(loader=loader, **options)6364 # convert requested filters65 for name in convert_filters:66 env.filters[name] = convert_django_filter(name)6768 # import templatetags of installed apps69 for app in settings.INSTALLED_APPS:70 try:71 __import__(app + '.templatetags')72 except ImportError:73 pass7475 # setup the django.contrib.jinja module76 setup_django_module()777879def setup_django_module():80 """81 create a new Jinja module for django.82 """83 from jinja.contrib import djangosupport84 module = contrib.jinja = sys.modules['django.contrib.jinja'] = \85 new.module('django.contrib.jinja')86 module.env = env87 module.__doc__ = djangosupport.__doc__88 module.register = Library89 public_names = module.__all__ = ['register', 'env']90 get_name = globals().get91 for name in exported:92 setattr(module, name, get_name(name))93 public_names.append(name)949596def render_to_response(template, context={}, request=None,97 mimetype=None):98 """This function will take a few variables and spit out a full webpage."""99 content = render_to_string(template, context, request)100 if mimetype is None:101 mimetype = settings.DEFAULT_CONTENT_TYPE102 return HttpResponse(content, mimetype)103104105def render_to_string(template, context={}, request=None):106 """Render a template to a string."""107 assert env is not None, 'Jinja not configured for django'108 if request is not None:109 context['request'] = request110 for processor in get_standard_processors():111 context.update(processor(request))112 template = env.get_template(template)113 return template.render(context)114115116def convert_django_filter(f):117 """Convert a django filter into a Jinja filter."""118 if isinstance(f, str):119 p = f.split('.')120 f = getattr(__import__('.'.join(p[:-1]), None, None, ['']), p[-1])121 def filter_factory(*args):122 def wrapped(env, ctx, value):123 return f(value, *args)124 return wrapped125 filter_factory.__name__ = f.__name__126 filter_factory.__doc__ = getattr(f, '__doc__', None)127 return filter_factory128129130class Library(object):131 """132 Continues a general feel of wrapping all the registration133 methods for easy importing.134135 This is available in `django.contrib.jinja` as `register`.136137 For more details see the docstring of the `django.contrib.jinja` module.138 """139 def object(func, name=None):140 """Register a new global."""141 if name is None:142 name = getattr(func, '__name__')143 env.globals[name] = func144 return func145 object = staticmethod(object)146147 def filter(func, name=None):148 """Register a new filter function."""149 if name is None:150 name = func.__name__151 env.filters[name] = func152 return func153 filter = staticmethod(filter)154155 def test(func, name):156 """Register a new test function."""157 if name is None:158 name = func.__name__159 env.tests[name] = func160 return func161 test = staticmethod(test)162163 def context_inclusion(func, template, name=None):164 """165 Similar to the inclusion tag from django this one expects func to be a166 function with a similar argument list to func(context, *args, **kwargs)167168 It passed in the current context allowing the function to edit it or read169 from it. the function must return a dict with which to pass into the170 renderer. Normally expected is an altered dictionary.171172 Note processors are NOT ran on this context.173 """174 def wrapper(env, context, *args, **kwargs):175 context = func(context.to_dict(), *args, **kwargs)176 return render_to_string(template, context)177 wrapper.jinja_context_callable = True178 if name is None:179 name = func.__name__180 try:181 wrapper.__name__ = func.__name__182 wrapper.__doc__ = func.__doc__183 except:184 pass185 env.globals[name] = wrapper186 context_inclusion = staticmethod(context_inclusion)187188 def clean_inclusion(func, template, name=None, run_processors=False):189 """190 Similar to above however it won't pass the context into func().191 Also the returned context will have the context processors run upon it.192 """193 def wrapper(env, context, *args, **kwargs):194 if run_processors:195 request = context['request']196 else:197 request = None198 context = func({}, *args, **kwargs)199 return render_to_string(template, context, request)200 wrapper.jinja_context_callable = True201 if name is None:202 name = func.__name__203 try:204 wrapper.__name__ = func.__name__205 wrapper.__doc__ = func.__doc__206 except:207 pass208 env.globals[name] = wrapper209 clean_inclusion = staticmethod(clean_inclusion)
added:jinja2/contrib/djangosupport.py+124 added
1# -*- coding: utf-8 -*-2"""3 jinja.contrib.djangosupport4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~56 Support for the django framework. This module is quite magical because it7 just exports one single function, the `configure` function which is used8 to create a new Jinja environment and setup a special module called9 `django.contrib.jinja` which exports a couple of functions useful for Jinja.1011 Quickstart12 ==========1314 To get started execute the following code at the bottom of your settings.py15 or in some general application file such as urls.py or a central module. The16 only thing that matters is that it's executed right *after* the settings17 were set up and *before* `django.contrib.jinja` is imported::1819 from jinja.contrib import djangosupport20 djangosupport.configure()2122 What this does is setting up a Jinja environment for this django instance23 with loaders for `TEMPLATE_DIRS` etc. It also converts a couple of default24 django filters such as `date` and `timesince` which are not available in25 Jinja per default. If you want to change the list you can provide others26 by passing a list with filter import names as `convert_filters` keyword27 argument.2829 All other keyword arguments are forwarded to the environment. If you want30 to provide a loader yourself pass it a loader keyword argument.3132 Rendering Templates33 ===================3435 To render a template you can use the functions `render_to_string` or36 `render_to_response` from the `django.contrib.jinja` module::3738 from django.contrib.jinja import render_to_response39 resp = render_to_response('Hello {{ username }}!', {40 'username': req.session['username']41 }, req)4243 `render_to_string` and `render_to_response` take at least the name of44 the template as argument, then the optional dict which will become the45 context. If you also provide a request object as third argument the46 context processors will be applied.4748 `render_to_response` also takes a forth parameter which can be the49 content type which defaults to `DEFAULT_CONTENT_TYPE`.5051 Converting Filters52 ==================5354 One of the useful objects provided by `django.contrib.jinja` is the55 `register` object which can be used to register filters, tests and56 global objects. You can also convert any filter django provides in57 a Jinja filter using `convert_django_filter`::5859 from django.contrib.jinja import register, convert_django_filter60 from django.template.defaultfilters import floatformat6162 register.filter(convert_django_filter(floatformat), 'floatformat')6364 Available methods on the `register` object:6566 ``object (obj[, name])``67 Register a new global as name or with the object's name.68 Returns the function object unchanged so that you can use69 it as decorator if no name is provided.7071 ``filter (func[, name])``72 Register a function as filter with the name provided or73 the object's name as filtername.74 Returns the function object unchanged so that you can use75 it as decorator if no name is provided.7677 ``test (func[, name])``78 Register a function as test with the name provided or the79 object's name as testname.80 Returns the function object unchanged so that you can use81 it as decorator if no name is provided.8283 ``context_inclusion (func, template[, name])``84 Register a function with a name provided or the func object's85 name in the global namespace that acts as subrender function.8687 func is called with the callers context as dict and the88 arguments and keywords argument of the inclusion function.89 The function should then process the context and return a90 new context or the same context object. Afterwards the91 template is rendered with this context.9293 Example::9495 def add_author(context, author=None):96 if author is not None:97 author = Author.objects.get(name=author)98 context['author'] = author99 return context100101 register.context_inclusion(add_author, 'author_details.html',102 'render_author_details')103104 You can use it in the template like this then::105106 {{ render_author_details('John Doe') }}107108 ``clean_inclusion (func, template[, name[, run_processors]]) ``109 Works like `context_inclusion` but doesn't use the calles110 context but an empty context. If `run_processors` is `True`111 it will lookup the context for a `request` object and pass112 it to the render function to apply context processors.113114 :copyright: 2007 by Armin Ronacher, Bryan McLemore.115 :license: BSD, see LICENSE for more details.116"""117try:118 __import__('django')119except ImportError:120 raise ImportError('installed django required for djangosupport')121else:122 from jinja.contrib._djangosupport import configure123124__all__ = ['configure']
added:jinja2/translators/__init__.py+29 added
1# -*- coding: utf-8 -*-2"""3 jinja.translators4 ~~~~~~~~~~~~~~~~~56 The submodules of this module provide translators for the jinja ast.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213class Translator(object):14 """15 Base class of all translators.16 """1718 def process(environment, tree, source=None):19 """20 Process the given ast with the rules defined in21 environment and return a translated version of it.22 The translated object can be anything. The python23 translator for example outputs Template instances,24 a javascript translator would probably output strings.2526 This is a static function.27 """28 pass29 process = staticmethod(process)
added:jinja2/translators/python.py+1115 added
1# -*- coding: utf-8 -*-2"""3 jinja.translators.python4 ~~~~~~~~~~~~~~~~~~~~~~~~56 This module translates a jinja ast into python code.78 This translator tries hard to keep Jinja sandboxed. All security9 relevant calls are wrapped by methods defined in the environment.10 This affects:1112 - method calls13 - attribute access14 - name resolution1516 It also adds debug symbols used by the traceback toolkit implemented17 in `jinja.utils`.1819 Implementation Details20 ======================2122 It might sound strange but the translator tries to keep the generated23 code readable as much as possible. This simplifies debugging the Jinja24 core a lot. The additional processing overhead is just relevant for25 the translation process, the additional comments and whitespace won't26 appear in the saved bytecode.2728 :copyright: 2007 by Armin Ronacher.29 :license: BSD, see LICENSE for more details.30"""31import re32import sys33from jinja import nodes34from jinja.nodes import get_nodes35from jinja.parser import Parser36from jinja.exceptions import TemplateSyntaxError37from jinja.translators import Translator38from jinja.datastructure import TemplateStream39from jinja.utils import set, capture_generator404142#: regular expression for the debug symbols43_debug_re = re.compile(r'^\s*\# DEBUG\(filename=(?P<filename>.*?), '44 r'lineno=(?P<lineno>\d+)\)$')4546# For Python versions without generator exit exceptions47try:48 GeneratorExit = GeneratorExit49except NameError:50 class GeneratorExit(Exception):51 pass5253# For Pythons without conditional expressions54try:55 exec '0 if 0 else 0'56 have_conditional_expr = True57except SyntaxError:58 have_conditional_expr = False596061class Template(object):62 """63 Represents a finished template.64 """6566 def __init__(self, environment, code):67 self.environment = environment68 self.code = code69 self.generate_func = None7071 def dump(self, stream=None):72 """Dump the template into python bytecode."""73 if stream is not None:74 from marshal import dump75 dump(self.code, stream)76 else:77 from marshal import dumps78 return dumps(self.code)7980 def load(environment, data):81 """Load the template from python bytecode."""82 if isinstance(data, basestring):83 from marshal import loads84 code = loads(data)85 else:86 from marshal import load87 code = load(data)88 return Template(environment, code)89 load = staticmethod(load)9091 def render(self, *args, **kwargs):92 """Render a template."""93 __traceback_hide__ = True94 ctx = self._prepare(*args, **kwargs)95 try:96 return capture_generator(self.generate_func(ctx))97 except:98 self._debug(ctx, *sys.exc_info())99100 def stream(self, *args, **kwargs):101 """Render a template as stream."""102 def proxy(ctx):103 try:104 for item in self.generate_func(ctx):105 yield item106 except GeneratorExit:107 return108 except:109 self._debug(ctx, *sys.exc_info())110 return TemplateStream(proxy(self._prepare(*args, **kwargs)))111112 def _prepare(self, *args, **kwargs):113 """Prepare the template execution."""114 # if there is no generation function we execute the code115 # in a new namespace and save the generation function and116 # debug information.117 env = self.environment118 if self.generate_func is None:119 ns = {'environment': env}120 exec self.code in ns121 self.generate_func = ns['generate']122 return env.context_class(env, *args, **kwargs)123124 def _debug(self, ctx, exc_type, exc_value, traceback):125 """Debugging Helper"""126 # just modify traceback if we have that feature enabled127 from traceback import print_exception128 print_exception(exc_type, exc_value, traceback)129130 if self.environment.friendly_traceback:131 # hook the debugger in132 from jinja.debugger import translate_exception133 exc_type, exc_value, traceback = translate_exception(134 self, ctx, exc_type, exc_value, traceback)135 print_exception(exc_type, exc_value, traceback)136137 raise exc_type, exc_value, traceback138139140class TranslationOperator(object):141 """142 A translation operator has a single string representing the operation143 """144 def __init__(self, operator, translator):145 self.operator = operator146 self.translator = translator147148class UnaryOperator(TranslationOperator):149 """150 A unary operator has one side to the operation.151 """152 def __call__(self, node):153 """154 Apply operator.155 """156 return '( %s %s)' % (157 self.operator,158 self.translator.handle_node(node.node),159 )160161class BinaryOperator(TranslationOperator):162 """163 A binary operator has two sides to the operation.164 """165 def __call__(self, node):166 """167 Apply operator.168 """169 return '(%s %s %s)' % (170 self.translator.handle_node(node.left),171 self.operator,172 self.translator.handle_node(node.right),173 )174175class PythonTranslator(Translator):176 """177 Pass this translator a ast tree to get valid python code.178 """179180 def __init__(self, environment, node, source):181 self.environment = environment182 self.loader = environment.loader.get_controlled_loader()183 self.node = node184 self.source = source185 self.closed = False186187 #: current level of indention188 self.indention = 0189 #: each {% cycle %} tag has a unique ID which increments190 #: automatically for each tag.191 self.last_cycle_id = 0192 #: set of used shortcuts jinja has to make local automatically193 self.used_shortcuts = set(['undefined_singleton'])194 #: set of used datastructures jinja has to import195 self.used_data_structures = set()196 #: set of used utils jinja has to import197 self.used_utils = set()198 #: flags for runtime error199 self.require_runtime_error = False200 #: do wee need a "set" object?201 self.need_set_import = False202 #: flag for regular expressions203 self.compiled_regular_expressions = {}204205 #: bind the nodes to the callback functions. There are206 #: some missing! A few are specified in the `unhandled`207 #: mapping in order to disallow their usage, some of them208 #: will not appear in the jinja parser output because209 #: they are filtered out.210 self.handlers = {211 # block nodes212 nodes.Template: self.handle_template,213 nodes.Text: self.handle_template_text,214 nodes.NodeList: self.handle_node_list,215 nodes.ForLoop: self.handle_for_loop,216 nodes.IfCondition: self.handle_if_condition,217 nodes.Cycle: self.handle_cycle,218 nodes.Print: self.handle_print,219 nodes.Macro: self.handle_macro,220 nodes.Call: self.handle_call,221 nodes.Set: self.handle_set,222 nodes.Filter: self.handle_filter,223 nodes.Block: self.handle_block,224 nodes.Include: self.handle_include,225 nodes.Trans: self.handle_trans,226227 # expression nodes228 nodes.NameExpression: self.handle_name,229 nodes.CompareExpression: self.handle_compare,230 nodes.TestExpression: self.handle_test,231 nodes.ConstantExpression: self.handle_const,232 nodes.RegexExpression: self.handle_regex,233 nodes.SubscriptExpression: self.handle_subscript,234 nodes.FilterExpression: self.handle_filter_expr,235 nodes.CallExpression: self.handle_call_expr,236 nodes.AddExpression: BinaryOperator('+', self),237 nodes.SubExpression: BinaryOperator('-', self),238 nodes.ConcatExpression: self.handle_concat,239 nodes.DivExpression: BinaryOperator('/', self),240 nodes.FloorDivExpression: BinaryOperator('//', self),241 nodes.MulExpression: BinaryOperator('*', self),242 nodes.ModExpression: BinaryOperator('%', self),243 nodes.PosExpression: UnaryOperator('+', self),244 nodes.NegExpression: UnaryOperator('-', self),245 nodes.PowExpression: BinaryOperator('**', self),246 nodes.DictExpression: self.handle_dict,247 nodes.SetExpression: self.handle_set_expr,248 nodes.ListExpression: self.handle_list,249 nodes.TupleExpression: self.handle_tuple,250 nodes.UndefinedExpression: self.handle_undefined,251 nodes.AndExpression: BinaryOperator(' and ', self),252 nodes.OrExpression: BinaryOperator(' or ', self),253 nodes.NotExpression: UnaryOperator(' not ', self),254 nodes.SliceExpression: self.handle_slice,255 nodes.ConditionalExpression: self.handle_conditional_expr256 }257258 # -- public methods259260 def process(environment, node, source=None):261 """262 The only public method. Creates a translator instance,263 translates the code and returns it in form of an264 `Template` instance.265 """266 translator = PythonTranslator(environment, node, source)267 filename = node.filename or '<template>'268 source = translator.translate()269 return Template(environment, compile(source, filename, 'exec'))270 process = staticmethod(process)271272 # -- private helper methods273274 def indent(self, text):275 """276 Indent the current text. This does only indent the277 first line.278 """279 return (' ' * (self.indention * 4)) + text280281 def to_tuple(self, args):282 """283 Return a tuple repr without nested repr.284 """285 return '(%s%s)' % (286 ', '.join(args),287 len(args) == 1 and ',' or ''288 )289290 def nodeinfo(self, node, force=False):291 """292 Return a comment that helds the node informations or None293 if there is no need to add a debug comment.294 """295 return '# DEBUG(filename=%s, lineno=%s)' % (296 node.filename or '',297 node.lineno298 )299300 def handle_node(self, node):301 """302 Handle one node. Resolves the correct callback functions defined303 in the callback mapping.304 """305 if self.closed:306 raise RuntimeError('translator is closed')307 if node.__class__ in self.handlers:308 return self.handlers[node.__class__](node)309 else:310 raise AssertionError('unhandled node %r' % node.__class__)311312 def close(self):313 """314 Clean up stuff.315 """316 self.closed = True317 self.handlers = self.node = self.environment = self.loader = None318319 def translate(self):320 """321 Translate the node defined in the constructor.322 """323 try:324 return self.handle_node(self.node)325 finally:326 self.close()327328 # -- jinja nodes329330 def handle_template(self, node):331 """332 Handle the overall template node. This node is the first node and333 ensures that we get the bootstrapping code. It also knows about334 inheritance information. It only occours as outer node, never in335 the tree itself.336 """337 self.indention = 1338339 # if there is a parent template we parse the parent template and340 # update the blocks there. Once this is done we drop the current341 # template in favor of the new one. Do that until we found the342 # root template.343 parent = None344 overwrites = {}345 blocks = {}346 requirements = []347 outer_filename = node.filename or '<template>'348349 # this set is required in order to not add blocks to the block350 # dict a second time if they were not overridden in one template351 # in the template chain.352 already_registered_block = set()353354 while node.extends is not None:355 # the direct child nodes in a template that are not blocks356 # are processed as template globals, thus executed *before*357 # the master layout template is loaded. This can be used358 # for further processing. The output of those nodes does359 # not appear in the final template.360 requirements += [child for child in node.body.get_child_nodes()361 if child.__class__ not in (nodes.Text,362 nodes.Block)]363364 # load the template we inherit from and add not known blocks.365 # this also marks the templates on the controlled loader but366 # are never removed. that's no problem because we don't allow367 # parents we extend from as includes and the controlled loader368 # is only used for this templated369 parent = self.loader.parse(node.extends,370 node.filename)371372 # look up all block nodes in the current template and373 # add them to the override dict.374 for n in get_nodes(nodes.Block, node):375 overwrites[n.name] = n376 # handle direct overrides377 for n in get_nodes(nodes.Block, parent):378 # an overwritten block for the parent template. handle that379 # override in the template and register it in the deferred380 # block dict.381 if n.name in overwrites and n not in already_registered_block:382 blocks.setdefault(n.name, []).append(n.clone())383 n.replace(overwrites[n.name])384 already_registered_block.add(n)385 # make the parent node the new node386 node = parent387388 # handle requirements code389 if requirements:390 requirement_lines = ['def bootstrap(context):']391 for n in requirements:392 requirement_lines.append(self.handle_node(n))393 requirement_lines.append(' if 0: yield None\n')394395 # handle body in order to get the used shortcuts396 body_code = self.handle_node(node.body)397398 # same for blocks in callables399 block_lines = []400 block_items = blocks.items()401 block_items.sort()402 dict_lines = []403 for name, items in block_items:404 tmp = []405 for idx, item in enumerate(items):406 # ensure that the indention is correct407 self.indention = 1408 func_name = 'block_%s_%s' % (name, idx)409 data = self.handle_block(item, idx + 1)410 # blocks with data411 if data:412 block_lines.extend([413 'def %s(context):' % func_name,414 self.indent(self.nodeinfo(item, True)),415 data,416 ' if 0: yield None\n'417 ])418 tmp.append('buffereater(%s)' % func_name)419 self.used_utils.add('buffereater')420 # blocks without data, can default to something421 # from utils422 else:423 tmp.append('empty_block')424 self.used_utils.add('empty_block')425 dict_lines.append(' %r: %s' % (426 str(name),427 self.to_tuple(tmp)428 ))429430 # bootstrapping code431 lines = ['# Essential imports', 'from __future__ import division']432 if self.used_utils:433 lines.append('from jinja.utils import %s' % \434 ', '.join(tuple(self.used_utils)))435 if self.require_runtime_error:436 lines.append('from jinja.exceptions import TemplateRuntimeError')437 if self.used_data_structures:438 lines.append('from jinja.datastructure import %s' % ', '.439 join(self.used_data_structures))440 if self.need_set_import:441 lines.append('from jinja.utils import set')442443 # compile regular expressions444 if self.compiled_regular_expressions:445 lines.append('import re')446 lines.append('\n# Compile used regular expressions')447 for regex, name in self.compiled_regular_expressions.iteritems():448 lines.append('%s = re.compile(%r)' % (name, regex))449450 lines.append(451 '\n# Aliases for some speedup\n'452 '%s\n\n'453 '# Marker for Jinja templates\n'454 '__jinja_template__ = True\n\n'455 '# Name for disabled debugging\n'456 '__name__ = %r\n\n'457 'def generate(context):\n'458 ' assert environment is context.environment' % (459 '\n'.join([460 '%s = environment.%s' % (item, item) for item in461 self.used_shortcuts462 ]),463 outer_filename464 )465 )466467 # the template body468 if requirements:469 lines.append(' for item in bootstrap(context): pass')470 lines.append(body_code)471 lines.append(' if 0: yield None\n')472473 # now write the bootstrapping (requirements) core if there is one474 if requirements:475 lines.append('# Bootstrapping code')476 lines.extend(requirement_lines)477478 # blocks must always be defined. even if it's empty. some479 # features depend on it480 if block_lines:481 lines.append('# Superable blocks')482 lines.extend(block_lines)483 lines.append('# Block mapping')484 if dict_lines:485 lines.append('blocks = {\n%s\n}\n' % ',\n'.join(dict_lines))486 else:487 lines.append('blocks = {}\n')488489 # now get the real source lines and map the debugging symbols490 debug_mapping = []491 file_mapping = {}492 last = None493 offset = -1494 sourcelines = ('\n'.join(lines)).splitlines()495 result = []496497 for idx, line in enumerate(sourcelines):498 m = _debug_re.search(line)499 if m is not None:500 d = m.groupdict()501 filename = d['filename'] or None502 if isinstance(filename, unicode):503 filename = filename.encode('utf-8')504 if filename in file_mapping:505 file_id = file_mapping[filename]506 else:507 file_id = file_mapping[filename] = 'F%d' % \508 len(file_mapping)509 this = (file_id, int(d['lineno']))510 # if it's the same as the line before we ignore it511 if this != last:512 debug_mapping.append('(%r, %s, %r)' % ((idx - offset,) + this))513 last = this514 # for each debug symbol the line number and so the offset515 # changes by one.516 offset += 1517 else:518 result.append(line)519520 # now print file mapping and debug info521 # the debug info:522 # debug_info binds template line numbers to generated523 # source lines. this information is always524 # present and part of the bytecode.525 # template_source only available if loaded from string to526 # get debug source code. Because this is527 # dumped too it's a bad idea to dump templates528 # loaded from a string.529 result.append('\n# Debug Information')530 file_mapping = file_mapping.items()531 file_mapping.sort(lambda a, b: cmp(a[1], b[1]))532 for filename, file_id in file_mapping:533 result.append('%s = %r' % (file_id, filename))534 result.append('debug_info = %s' % self.to_tuple(debug_mapping))535 result.append('template_source = %r' % self.source)536537 return '\n'.join(result)538539 def handle_template_text(self, node):540 """541 Handle data around nodes.542 """543 # special case: no variables544 if not node.variables:545 return self.indent(self.nodeinfo(node)) + '\n' + \546 self.indent('yield %r' % node.text.replace('%%', '%'))547548 # special case: one variable, no text549 self.used_shortcuts.add('finish_var')550 if len(node.variables) == 1 and node.text == '%s':551 return self.indent(self.nodeinfo(node)) + '\n' + \552 self.indent('yield finish_var(%s, context)' %553 self.handle_node(node.variables[0]))554555 # all other cases556 buf = []557 write = lambda x: buf.append(self.indent(x))558559 write(self.nodeinfo(node))560 write('yield %r %% (' % node.text)561 self.indention += 1562 for var in node.variables:563 write(self.nodeinfo(var))564 write('finish_var(%s, context)' % self.handle_node(var) + ',')565 self.indention -= 1566 write(')')567568 return '\n'.join(buf)569570 def handle_node_list(self, node):571 """572 In some situations we might have a node list. It's just573 a collection of multiple statements.574575 If the nodelist was empty it will return an empty string576 """577 body = '\n'.join([self.handle_node(n) for n in node])578 if body:579 return self.indent(self.nodeinfo(node)) + '\n' + body580 return ''581582 def handle_for_loop(self, node):583 """584 Handle a for loop. Pretty basic, just that we give the else585 clause a different behavior.586 """587 self.used_data_structures.add('LoopContext')588 buf = []589 write = lambda x: buf.append(self.indent(x))590 write(self.nodeinfo(node))591 write('context.push()')592593 # recursive loops594 if node.recursive:595 write('def loop(seq):')596 self.indention += 1597 write('for %s in context[\'loop\'].push(seq):' %598 self.handle_node(node.item),599 )600601 # simple loops602 else:603 write('context[\'loop\'] = loop = LoopContext(%s, '604 'context[\'loop\'], None)' % self.handle_node(node.seq))605 write('for %s in loop:' %606 self.handle_node(node.item)607 )608609 # handle real loop code610 self.indention += 1611 write(self.nodeinfo(node.body))612 if node.body:613 buf.append(self.handle_node(node.body))614 else:615 write('pass')616 self.indention -= 1617618 # else part of loop619 if node.else_:620 write('if not context[\'loop\'].iterated:')621 self.indention += 1622 write(self.nodeinfo(node.else_))623 buf.append(self.handle_node(node.else_) or self.indent('pass'))624 self.indention -= 1625626 # call recursive for loop!627 if node.recursive:628 write('context[\'loop\'].pop()')629 write('if 0: yield None')630 self.indention -= 1631 write('context[\'loop\'] = LoopContext(None, context[\'loop\'], '632 'buffereater(loop))')633 self.used_utils.add('buffereater')634 write('for item in loop(%s):' % self.handle_node(node.seq))635 self.indention += 1636 write('yield item')637 self.indention -= 1638639 write('context.pop()')640 return '\n'.join(buf)641642 def handle_if_condition(self, node):643 """644 Handle an if condition node.645 """646 buf = []647 write = lambda x: buf.append(self.indent(x))648 write(self.nodeinfo(node))649 for idx, (test, body) in enumerate(node.tests):650 write('%sif %s:' % (651 idx and 'el' or '',652 self.handle_node(test)653 ))654 self.indention += 1655 write(self.nodeinfo(body))656 buf.append(self.handle_node(body) or self.indent('pass'))657 self.indention -= 1658 if node.else_ is not None:659 write('else:')660 self.indention += 1661 write(self.nodeinfo(node.else_))662 buf.append(self.handle_node(node.else_) or self.indent('pass'))663 self.indention -= 1664 return '\n'.join(buf)665666 def handle_cycle(self, node):667 """668 Handle the cycle tag.669 """670 self.used_data_structures.add('CycleContext')671 name = '::cycle_%x' % self.last_cycle_id672 self.last_cycle_id += 1673 buf = []674 write = lambda x: buf.append(self.indent(x))675676 write('if %r not in context.current:' % name)677 self.indention += 1678 write(self.nodeinfo(node))679 if node.seq.__class__ in (nodes.TupleExpression,680 nodes.ListExpression):681 write('context.current[%r] = CycleContext(%s)' % (682 name,683 self.to_tuple([self.handle_node(n) for n in node.seq.items])684 ))685 hardcoded = True686 else:687 write('context.current[%r] = CycleContext()' % name)688 hardcoded = False689 self.indention -= 1690691 self.used_shortcuts.add('finish_var')692 if hardcoded:693 write('yield finish_var(context.current[%r].cycle(), '694 'context)' % name)695 else:696 write('yield finish_var(context.current[%r].cycle(%s), '697 'context)' % (698 name,699 self.handle_node(node.seq)700 ))701702 return '\n'.join(buf)703704 def handle_print(self, node):705 """706 Handle a print statement.707 """708 self.used_shortcuts.add('finish_var')709 return self.indent(self.nodeinfo(node)) + '\n' +\710 self.indent('yield finish_var(%s, context)' %711 self.handle_node(node.expr))712713 def handle_macro(self, node):714 """715 Handle macro declarations.716 """717 buf = []718 write = lambda x: buf.append(self.indent(x))719720 write('def macro(*args, **kw):')721 self.indention += 1722 write(self.nodeinfo(node))723724 # collect macro arguments725 arg_items = []726 caller_overridden = False727728 # if we have conditional expressions available in that python729 # build (for example cpython > 2.4) we can use them, they730 # will perform slightly better.731 if have_conditional_expr:732 arg_tmpl = '\'%(name)s\': args[%(pos)d] if argcount > %(pos)d ' \733 'else %(default)s'734 # otherwise go with the and/or tuple hack:735 else:736 arg_tmpl = '\'%(name)s\': (argcount > %(pos)d and '\737 '(args[%(pos)d],) or (%(default)s,))[0]'738739 if node.arguments:740 varargs_init = '\'varargs\': args[%d:]' % len(node.arguments)741 write('argcount = len(args)')742 for idx, (name, n) in enumerate(node.arguments):743 arg_items.append(arg_tmpl % {744 'name': name,745 'pos': idx,746 'default': n is None and 'undefined_singleton' or747 self.handle_node(n)748 })749 if name == 'caller':750 caller_overridden = True751 elif name == 'varargs':752 varargs_init = None753 else:754 varargs_init = '\'varargs\': args'755756 if caller_overridden:757 write('kw.pop(\'caller\', None)')758 else:759 arg_items.append('\'caller\': kw.pop(\'caller\', undefined_singleton)')760 if varargs_init:761 arg_items.append(varargs_init)762763 write('context.push({%s})' % ',\n '.join([764 idx and self.indent(item) or item for idx, item765 in enumerate(arg_items)766 ]))767768 # disallow any keyword arguments769 write('if kw:')770 self.indention += 1771 write('raise TemplateRuntimeError(\'%s got an unexpected keyword '772 'argument %%r\' %% iter(kw).next())' % node.name)773 self.require_runtime_error = True774 self.indention -= 1775776 write(self.nodeinfo(node.body))777 data = self.handle_node(node.body)778 if data:779 buf.append(data)780 write('context.pop()')781 write('if 0: yield None')782 self.indention -= 1783 buf.append(self.indent('context[%r] = buffereater(macro, True)' %784 node.name))785 self.used_utils.add('buffereater')786787 return '\n'.join(buf)788789 def handle_call(self, node):790 """791 Handle extended macro calls.792 """793 buf = []794 write = lambda x: buf.append(self.indent(x))795796 write('def call(**kwargs):')797 self.indention += 1798 write('context.push(kwargs)')799 data = self.handle_node(node.body)800 if data:801 buf.append(data)802 write('context.pop()')803 write('if 0: yield None')804 self.indention -= 1805 write('yield ' + self.handle_call_expr(node.expr,806 {'caller': 'buffereater(call)'}))807 self.used_utils.add('buffereater')808809 return '\n'.join(buf)810811 def handle_set(self, node):812 """813 Handle variable assignments.814 """815 if node.scope_local:816 tmpl = 'context[%r] = %s'817 else:818 tmpl = 'context.set_nonlocal(%r, %s)'819 return self.indent(self.nodeinfo(node)) + '\n' + \820 self.indent(tmpl % (821 node.name,822 self.handle_node(node.expr)823 ))824825 def handle_filter(self, node):826 """827 Handle filter sections.828 """829 buf = []830 write = lambda x: buf.append(self.indent(x))831 write('def filtered():')832 self.indention += 1833 write('context.push()')834 write(self.nodeinfo(node.body))835 data = self.handle_node(node.body)836 if data:837 buf.append(data)838 write('context.pop()')839 write('if 0: yield None')840 self.indention -= 1841 self.used_shortcuts.add('apply_filters')842 write('yield apply_filters(buffereater(filtered)(), context, %s)' %843 self.to_tuple(['(%r, %s)' % (844 name,845 self.to_tuple(map(self.handle_node, args))846 ) for name, args in node.filters])847 )848 self.used_utils.add('buffereater')849 return '\n'.join(buf)850851 def handle_block(self, node, level=0):852 """853 Handle blocks in the sourcecode. We only use them to854 call the current block implementation that is stored somewhere855 else.856 """857 rv = self.handle_node(node.body)858 if not rv:859 return ''860861 self.used_data_structures.add('SuperBlock')862 buf = []863 write = lambda x: buf.append(self.indent(x))864865 write(self.nodeinfo(node))866 write('context.push({\'super\': SuperBlock(%r, blocks, %r, context)})' % (867 str(node.name),868 level869 ))870 write(self.nodeinfo(node.body))871 buf.append(rv)872 write('context.pop()')873 return '\n'.join(buf)874875 def handle_include(self, node):876 """877 Include another template at the current position.878 """879 tmpl = self.loader.parse(node.template,880 node.filename)881 try:882 return self.handle_node(tmpl.body)883 finally:884 self.loader.mark_as_processed()885886 def handle_trans(self, node):887 """888 Handle translations.889 """890 if node.replacements:891 replacements = []892 for name, n in node.replacements.iteritems():893 replacements.append('%r: %s' % (894 name,895 self.handle_node(n)896 ))897 replacements = '{%s}' % ', '.join(replacements)898 else:899 replacements = 'None'900 return self.indent(self.nodeinfo(node)) + '\n' +\901 self.indent('yield context.translate_func(%r, %r, %r, %s)' % (902 node.singular,903 node.plural,904 node.indicator,905 replacements906 ))907908 # -- python nodes909910 def handle_name(self, node):911 """912 Handle name assignments and name retreivement.913 """914 if node.name == '_':915 return 'context.translate_func'916 return 'context[%r]' % node.name917918 def handle_compare(self, node):919 """920 Any sort of comparison921 """922 ops = {923 'eq': '==',924 'ne': '!=',925 'lt': '<',926 'lteq': '<=',927 'gt': '>',928 'gteq': '>=',929 'in': 'in',930 'not in': 'not in'931 }932 buf = []933 buf.append(self.handle_node(node.expr))934 for op, n in node.ops:935 buf.append(ops[op])936 buf.append(self.handle_node(n))937 return ' '.join(buf)938939 def handle_test(self, node):940 """941 Handle test calls.942 """943 self.used_shortcuts.add('perform_test')944 return 'perform_test(context, %r, %s, %s)' % (945 node.name,946 self.to_tuple([self.handle_node(n) for n in node.args]),947 self.handle_node(node.node)948 )949950 def handle_const(self, node):951 """952 Constant values in expressions.953 """954 return repr(node.value)955956 def handle_regex(self, node):957 """958 Regular expression literals.959 """960 if self.environment.disable_regexps:961 raise TemplateSyntaxError('regular expressions disabled.')962 if node.value in self.compiled_regular_expressions:963 return self.compiled_regular_expressions[node.value]964 name = 'regex_%d' % len(self.compiled_regular_expressions)965 self.compiled_regular_expressions[node.value] = name966 return name967968 def handle_subscript(self, node):969 """970 Handle variable based attribute access foo['bar'].971 """972 self.used_shortcuts.add('get_attribute')973 if node.arg.__class__ is nodes.SliceExpression:974 rv = self.handle_slice(node.arg, getslice_test=True)975 if rv is not None:976 return self.handle_node(node.node) + rv977 return 'get_attribute(%s, %s)' % (978 self.handle_node(node.node),979 self.handle_node(node.arg)980 )981982 def handle_tuple(self, node):983 """984 Tuple unpacking loops.985 """986 return self.to_tuple([self.handle_node(n) for n in node.items])987988 def handle_filter_expr(self, node):989 """990 We use the pipe operator for filtering.991 """992 self.used_shortcuts.add('apply_filters')993 return 'apply_filters(%s, context, %s)' % (994 self.handle_node(node.node),995 self.to_tuple(['(%r, %s)' % (996 name,997 self.to_tuple(map(self.handle_node, args))998 ) for name, args in node.filters])999 )10001001 def handle_call_expr(self, node, extra_kwargs=None):1002 """1003 Handle function calls.1004 """1005 args = []1006 kwargs = {}1007 dyn_args = dyn_kwargs = None1008 if node.dyn_args is not None:1009 dyn_args = self.handle_node(node.dyn_args)1010 if node.dyn_kwargs is not None:1011 dyn_kwargs = self.handle_node(node.dyn_kwargs)1012 for arg in node.args:1013 args.append(self.handle_node(arg))1014 for name, arg in node.kwargs:1015 kwargs[name] = self.handle_node(arg)1016 if extra_kwargs:1017 kwargs.update(extra_kwargs)1018 if not (args or kwargs or dyn_args or dyn_kwargs):1019 self.used_shortcuts.add('call_function_simple')1020 return 'call_function_simple(%s, context)' % \1021 self.handle_node(node.node)1022 self.used_shortcuts.add('call_function')1023 return 'call_function(%s, context, %s, {%s}, %s, %s)' % (1024 self.handle_node(node.node),1025 self.to_tuple(args),1026 ', '.join(['%r: %s' % i for i in kwargs.iteritems()]),1027 dyn_args,1028 dyn_kwargs1029 )10301031 def handle_concat(self, node):1032 """1033 Convert some objects to unicode and concatenate them.1034 """1035 self.used_shortcuts.add('to_unicode')1036 return "u''.join(%s)" % self.to_tuple([1037 'to_unicode(%s)' % self.handle_node(arg)1038 for arg in node.args1039 ])104010411042 def handle_dict(self, node):1043 """1044 Dict constructor syntax.1045 """1046 return '{%s}' % ', '.join([1047 '%s: %s' % (1048 self.handle_node(key),1049 self.handle_node(value)1050 ) for key, value in node.items1051 ])10521053 def handle_set_expr(self, node):1054 """1055 Set constructor syntax.1056 """1057 self.need_set_import = True1058 return 'set([%s])' % ', '.join([self.handle_node(n)1059 for n in node.items])10601061 def handle_list(self, node):1062 """1063 We don't know tuples, tuples are lists for jinja.1064 """1065 return '[%s]' % ', '.join([1066 self.handle_node(n) for n in node.items1067 ])10681069 def handle_undefined(self, node):1070 """1071 Return the current undefined literal.1072 """1073 return 'undefined_singleton'107410751076 def handle_slice(self, node, getslice_test=False):1077 """1078 Slice access. Because of backwards compatibilty to python's1079 `__getslice__` this function takes a second parameter that lets this1080 method return a regular slice bracket call. If a regular slice bracket1081 call that is compatible to __getslice__ is not possible the return1082 value will be `None` so that a regular `get_attribute` wrapping can1083 happen.1084 """1085 if node.start is None:1086 start = not getslice_test and 'None' or ''1087 else:1088 start = self.handle_node(node.start)1089 if node.stop is None:1090 stop = not getslice_test and 'None' or ''1091 else:1092 stop = self.handle_node(node.stop)1093 if node.step is None:1094 step = 'None'1095 else:1096 if getslice_test:1097 return1098 step = self.handle_node(node.step)1099 if getslice_test:1100 return '[%s:%s]' % (start, stop)1101 return 'slice(%s, %s, %s)' % (start, stop, step)11021103 def handle_conditional_expr(self, node):1104 """1105 Handle conditional expressions.1106 """1107 if have_conditional_expr:1108 tmpl = '%(expr1)s if %(test)s else %(expr2)s'1109 else:1110 tmpl = '(%(test)s and (%(expr1)s,) or (%(expr2)s,))[0]'1111 return tmpl % {1112 'test': self.handle_node(node.test),1113 'expr1': self.handle_node(node.expr1),1114 'expr2': self.handle_node(node.expr2)1115 }
added:jinja2/__init__.py+58 added
1# -*- coding: utf-8 -*-2"""3 jinja24 ~~~~~~56 Jinja is a `sandboxed`_ template engine written in pure Python. It7 provides a `Django`_ like non-XML syntax and compiles templates into8 executable python code. It's basically a combination of Django templates9 and python code.1011 Nutshell12 --------1314 Here a small example of a Jinja template::1516 {% extends 'base.html' %}17 {% block title %}Memberlist{% endblock %}18 {% block content %}19 <ul>20 {% for user in users %}21 <li><a href="{{ user.url|e }}">{{ user.username|e }}</a></li>22 {% endfor %}23 </ul>24 {% endblock %}2526 Philosophy27 ----------2829 Application logic is for the controller but don't try to make the life30 for the template designer too hard by giving him too few functionality.3132 For more informations visit the new `jinja webpage`_ and `documentation`_.3334 Note35 ----3637 This is the Jinja 1.0 release which is completely incompatible with the38 old "pre 1.0" branch. The old branch will still receive security updates39 and bugfixes but the 1.0 branch will be the only version that receives40 support.4142 If you have an application that uses Jinja 0.9 and won't be updated in43 the near future the best idea is to ship a Jinja 0.9 checkout together44 with the application.4546 The `Jinja tip`_ is installable via `easy_install` with ``easy_install47 Jinja==dev``.4849 .. _sandboxed: http://en.wikipedia.org/wiki/Sandbox_(computer_security)50 .. _Django: http://www.djangoproject.com/51 .. _jinja webpage: http://jinja.pocoo.org/52 .. _documentation: http://jinja.pocoo.org/documentation/index.html53 .. _Jinja tip: http://dev.pocoo.org/hg/jinja-main/archive/tip.tar.gz#egg=Jinja-dev545556 :copyright: 2008 by Armin Ronacher.57 :license: BSD, see LICENSE for more details.58"""
added:jinja2/_debugger.c+65 added
1/**2 * Jinja Extended Debugger3 * ~~~~~~~~~~~~~~~~~~~~~~~4 *5 * this module allows the jinja debugger to set the tb_next flag6 * on traceback objects. This is required to inject a traceback into7 * another one.8 *9 * For better windows support (not everybody has a visual studio 200310 * at home) it would be a good thing to have a ctypes implementation, but11 * because the struct is not exported there is currently no sane way.12 *13 * :copyright: 2007 by Armin Ronacher.14 * :license: BSD, see LICENSE for more details.15 */1617#include <Python.h>181920/**21 * set the tb_next attribute of a traceback object22 */23static PyObject *24tb_set_next(PyObject *self, PyObject *args)25{26 PyTracebackObject *tb, *old;27 PyObject *next;2829 if (!PyArg_ParseTuple(args, "O!O:tb_set_next", &PyTraceBack_Type, &tb, &next))30 return NULL;31 if (next == Py_None)32 next = NULL;33 else if (!PyTraceBack_Check(next)) {34 PyErr_SetString(PyExc_TypeError,35 "tb_set_next arg 2 must be traceback or None");36 return NULL;37 }38 else39 Py_INCREF(next);4041 old = tb->tb_next;42 tb->tb_next = (PyTracebackObject*)next;43 Py_XDECREF(old);4445 Py_INCREF(Py_None);46 return Py_None;47}484950static PyMethodDef module_methods[] = {51 {"tb_set_next", (PyCFunction)tb_set_next, METH_VARARGS,52 "Set the tb_next member of a traceback object."},53 {NULL, NULL, 0, NULL} /* Sentinel */54};5556#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */57#define PyMODINIT_FUNC void58#endif59PyMODINIT_FUNC60init_debugger(void)61{62 PyObject *module = Py_InitModule3("jinja._debugger", module_methods, "");63 if (!module)64 return;65}
added:jinja2/_native.py+85 added
1# -*- coding: utf-8 -*-2"""3 jinja._native4 ~~~~~~~~~~~~~56 This module implements the native base classes in case of not7 having a jinja with the _speedups module compiled.89 Note that if you change semantics here you have to edit the10 _speedups.c file to in order to support those changes for jinja11 setups with enabled speedup module.1213 :copyright: 2007 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15"""16from jinja.datastructure import Deferred17from jinja.utils import deque181920class BaseContext(object):2122 def __init__(self, undefined_singleton, globals, initial):23 self._undefined_singleton = undefined_singleton24 self.current = current = {}25 self._stack = deque([current, initial, globals])26 self.globals = globals27 self.initial = initial2829 self._push = self._stack.appendleft30 self._pop = self._stack.popleft3132 def stack(self):33 return list(self._stack)[::-1]34 stack = property(stack)3536 def pop(self):37 """Pop the last layer from the stack and return it."""38 rv = self._pop()39 self.current = self._stack[0]40 return rv4142 def push(self, data=None):43 """44 Push one layer to the stack and return it. Layer must be45 a dict or omitted.46 """47 data = data or {}48 self._push(data)49 self.current = self._stack[0]50 return data5152 def __getitem__(self, name):53 """54 Resolve one item. Restrict the access to internal variables55 such as ``'::cycle1'``. Resolve deferreds.56 """57 if not name.startswith('::'):58 for d in self._stack:59 if name in d:60 rv = d[name]61 if rv.__class__ is Deferred:62 rv = rv(self, name)63 # never touch the globals!64 if d is self.globals:65 self.initial[name] = rv66 else:67 d[name] = rv68 return rv69 return self._undefined_singleton7071 def __setitem__(self, name, value):72 """Set a variable in the outermost layer."""73 self.current[name] = value7475 def __delitem__(self, name):76 """Delete a variable in the outermost layer."""77 if name in self.current:78 del self.current[name]7980 def __contains__(self, name):81 """ Check if the context contains a given variable."""82 for layer in self._stack:83 if name in layer:84 return True85 return False
added:jinja2/_speedups.c+499 added
1/**2 * jinja._speedups3 * ~~~~~~~~~~~~~~~4 *5 * This module implements the BaseContext, a c implementation of the6 * Context baseclass. If this extension is not compiled the datastructure7 * module implements a class in python.8 *9 * Note that if you change semantics here you have to edit the _native.py10 * to in order to support those changes for jinja setups without the11 * speedup module too.12 *13 * :copyright: 2007 by Armin Ronacher.14 * :license: BSD, see LICENSE for more details.15 */1617#include <Python.h>18#include <structmember.h>1920/* Set by init_constants to real values */21static PyObject *Deferred;2223/**24 * Internal struct used by BaseContext to store the25 * stacked namespaces.26 */27struct StackLayer {28 PyObject *dict; /* current value, a dict */29 struct StackLayer *prev; /* lower struct layer or NULL */30};3132/**33 * BaseContext python class.34 */35typedef struct {36 PyObject_HEAD37 struct StackLayer *globals; /* the dict for the globals */38 struct StackLayer *initial; /* initial values */39 struct StackLayer *current; /* current values */40 long stacksize; /* current size of the stack */41 PyObject *undefined_singleton; /* the singleton returned on missing values */42} BaseContext;4344/**45 * Called by init_speedups in order to retrieve references46 * to some exceptions and classes defined in jinja python modules47 */48static int49init_constants(void)50{51 PyObject *datastructure = PyImport_ImportModule("jinja.datastructure");52 if (!datastructure)53 return 0;54 Deferred = PyObject_GetAttrString(datastructure, "Deferred");55 Py_DECREF(datastructure);56 return 1;57}5859/**60 * GC Helper61 */62static int63BaseContext_clear(BaseContext *self)64{65 struct StackLayer *current = self->current, *tmp;66 while (current) {67 tmp = current;68 Py_XDECREF(current->dict);69 current->dict = NULL;70 current = tmp->prev;71 PyMem_Free(tmp);72 }73 self->current = NULL;74 return 0;75}7677/**78 * Deallocator for BaseContext.79 *80 * Frees the memory for the stack layers before freeing the object.81 */82static void83BaseContext_dealloc(BaseContext *self)84{85 BaseContext_clear(self);86 self->ob_type->tp_free((PyObject*)self);87}8889/**90 * GC Helper91 */92static int93BaseContext_traverse(BaseContext *self, visitproc visit, void *args)94{95 int vret;96 struct StackLayer *layer = self->current;9798 while (layer) {99 vret = visit(layer->dict, args);100 if (vret != 0)101 return vret;102 layer = layer->prev;103 }104105 return 0;106}107108/**109 * Initializes the BaseContext.110 *111 * Like the native python class it takes a reference to the undefined112 * singleton which will be used for undefined values.113 * The other two arguments are the global namespace and the initial114 * namespace which usually contains the values passed to the render115 * function of the template. Both must be dicts.116 */117static int118BaseContext_init(BaseContext *self, PyObject *args, PyObject *kwds)119{120 PyObject *undefined = NULL, *globals = NULL, *initial = NULL;121122 if (!PyArg_ParseTuple(args, "OOO", &undefined, &globals, &initial))123 return -1;124 if (!PyDict_Check(globals) || !PyDict_Check(initial)) {125 PyErr_SetString(PyExc_TypeError, "stack layers must be dicts.");126 return -1;127 }128129 self->current = PyMem_Malloc(sizeof(struct StackLayer));130 self->current->prev = NULL;131 self->current->dict = PyDict_New();132 if (!self->current->dict)133 return -1;134135 self->initial = PyMem_Malloc(sizeof(struct StackLayer));136 self->initial->prev = NULL;137 self->initial->dict = initial;138 Py_INCREF(initial);139 self->current->prev = self->initial;140141 self->globals = PyMem_Malloc(sizeof(struct StackLayer));142 self->globals->prev = NULL;143 self->globals->dict = globals;144 Py_INCREF(globals);145 self->initial->prev = self->globals;146147 self->undefined_singleton = undefined;148 Py_INCREF(undefined);149150 self->stacksize = 3;151 return 0;152}153154/**155 * Pop the highest layer from the stack and return it156 */157static PyObject*158BaseContext_pop(BaseContext *self)159{160 PyObject *result;161 struct StackLayer *tmp = self->current;162163 if (self->stacksize <= 3) {164 PyErr_SetString(PyExc_IndexError, "stack too small.");165 return NULL;166 }167 result = self->current->dict;168 assert(result);169 self->current = tmp->prev;170 PyMem_Free(tmp);171 self->stacksize--;172 /* Took the reference to result from the struct. */173 return result;174}175176/**177 * Push a new layer to the stack and return it. If no parameter178 * is provided an empty dict is created. Otherwise the dict passed179 * to it is used as new layer.180 */181static PyObject*182BaseContext_push(BaseContext *self, PyObject *args)183{184 PyObject *value = NULL;185 struct StackLayer *new;186187 if (!PyArg_ParseTuple(args, "|O:push", &value))188 return NULL;189 if (!value) {190 value = PyDict_New();191 if (!value)192 return NULL;193 }194 else if (!PyDict_Check(value)) {195 PyErr_SetString(PyExc_TypeError, "dict required.");196 return NULL;197 }198 else199 Py_INCREF(value);200 new = PyMem_Malloc(sizeof(struct StackLayer));201 if (!new) {202 Py_DECREF(value);203 return NULL;204 }205 new->dict = value;206 new->prev = self->current;207 self->current = new;208 self->stacksize++;209 Py_INCREF(value);210 return value;211}212213/**214 * Getter that creates a list representation of the internal215 * stack. Used for compatibility with the native python implementation.216 */217static PyObject*218BaseContext_getstack(BaseContext *self, void *closure)219{220 int idx = 0;221 struct StackLayer *current = self->current;222 PyObject *result = PyList_New(self->stacksize);223 if (!result)224 return NULL;225 while (current) {226 Py_INCREF(current->dict);227 PyList_SET_ITEM(result, idx++, current->dict);228 current = current->prev;229 }230 PyList_Reverse(result);231 return result;232}233234/**235 * Getter that returns a reference to the current layer in the context.236 */237static PyObject*238BaseContext_getcurrent(BaseContext *self, void *closure)239{240 Py_INCREF(self->current->dict);241 return self->current->dict;242}243244/**245 * Getter that returns a reference to the initial layer in the context.246 */247static PyObject*248BaseContext_getinitial(BaseContext *self, void *closure)249{250 Py_INCREF(self->initial->dict);251 return self->initial->dict;252}253254/**255 * Getter that returns a reference to the global layer in the context.256 */257static PyObject*258BaseContext_getglobals(BaseContext *self, void *closure)259{260 Py_INCREF(self->globals->dict);261 return self->globals->dict;262}263264/**265 * Implements the context lookup.266 *267 * This works exactly like the native implementation but a lot268 * faster. It disallows access to internal names (names that start269 * with "::") and resolves Deferred values.270 */271static PyObject*272BaseContext_getitem(BaseContext *self, PyObject *item)273{274 PyObject *result;275 char *name = NULL;276 int isdeferred;277 struct StackLayer *current = self->current;278 279 /* allow unicode keys as long as they are ascii keys */280 if (PyUnicode_CheckExact(item)) {281 item = PyUnicode_AsASCIIString(item);282 if (!item)283 goto missing;284 }285 else if (!PyString_Check(item))286 goto missing;287288 /* disallow access to internal jinja values */289 name = PyString_AS_STRING(item);290 if (name[0] == ':' && name[1] == ':')291 goto missing;292293 while (current) {294 /* GetItemString just builds a new string from "name" again... */295 result = PyDict_GetItem(current->dict, item);296 if (!result) {297 current = current->prev;298 continue;299 }300 isdeferred = PyObject_IsInstance(result, Deferred);301 if (isdeferred == -1)302 return NULL;303 else if (isdeferred) {304 PyObject *namespace;305 PyObject *resolved = PyObject_CallFunctionObjArgs(306 result, self, item, NULL);307 if (!resolved)308 return NULL;309310 /* never touch the globals */311 if (current == self->globals)312 namespace = self->initial->dict;313 else314 namespace = current->dict;315 if (PyDict_SetItem(namespace, item, resolved) < 0)316 return NULL;317 Py_INCREF(resolved);318 return resolved;319 }320 Py_INCREF(result);321 return result;322 }323324missing:325 Py_INCREF(self->undefined_singleton);326 return self->undefined_singleton;327}328329/**330 * Check if the context contains a given value.331 */332static int333BaseContext_contains(BaseContext *self, PyObject *item)334{335 char *name;336 struct StackLayer *current = self->current;337338 /* allow unicode objects as keys as long as they are ASCII */339 if (PyUnicode_CheckExact(item)) {340 item = PyUnicode_AsASCIIString(item);341 if (!item)342 return 0;343 }344 else if (!PyString_Check(item))345 return 0;346347 name = PyString_AS_STRING(item);348 if (name[0] == ':' && name[1] == ':')349 return 0;350351 while (current) {352 /* XXX: for 2.4 and newer, use PyDict_Contains */353 if (!PyMapping_HasKey(current->dict, item)) {354 current = current->prev;355 continue;356 }357 return 1;358 }359360 return 0;361}362363/**364 * Set an value in the highest layer or delete one.365 */366static int367BaseContext_setitem(BaseContext *self, PyObject *item, PyObject *value)368{369 /* allow unicode objects as keys as long as they are ASCII */370 if (PyUnicode_CheckExact(item)) {371 item = PyUnicode_AsASCIIString(item);372 if (!item) {373 PyErr_Clear();374 goto error;375 }376 }377 else if (!PyString_Check(item))378 goto error;379 if (!value)380 return PyDict_DelItem(self->current->dict, item);381 return PyDict_SetItem(self->current->dict, item, value);382383error:384 PyErr_SetString(PyExc_TypeError, "expected string argument");385 return -1;386}387388389static PyGetSetDef BaseContext_getsetters[] = {390 {"stack", (getter)BaseContext_getstack, NULL,391 "a read only copy of the internal stack", NULL},392 {"current", (getter)BaseContext_getcurrent, NULL,393 "reference to the current layer on the stack", NULL},394 {"initial", (getter)BaseContext_getinitial, NULL,395 "reference to the initial layer on the stack", NULL},396 {"globals", (getter)BaseContext_getglobals, NULL,397 "reference to the global layer on the stack", NULL},398 {NULL} /* Sentinel */399};400401static PyMethodDef BaseContext_methods[] = {402 {"pop", (PyCFunction)BaseContext_pop, METH_NOARGS,403 "ctx.pop() -> dict\n\n"404 "Pop the last layer from the stack and return it."},405 {"push", (PyCFunction)BaseContext_push, METH_VARARGS,406 "ctx.push([layer]) -> layer\n\n"407 "Push one layer to the stack. Layer must be a dict "408 "or omitted."},409 {NULL} /* Sentinel */410};411412static PySequenceMethods BaseContext_as_sequence = {413 0, /* sq_length */414 0, /* sq_concat */415 0, /* sq_repeat */416 0, /* sq_item */417 0, /* sq_slice */418 0, /* sq_ass_item */419 0, /* sq_ass_slice */420 (objobjproc)BaseContext_contains,/* sq_contains */421 0, /* sq_inplace_concat */422 0 /* sq_inplace_repeat */423};424425static PyMappingMethods BaseContext_as_mapping = {426 NULL,427 (binaryfunc)BaseContext_getitem,428 (objobjargproc)BaseContext_setitem429};430431static PyTypeObject BaseContextType = {432 PyObject_HEAD_INIT(NULL)433 0, /* ob_size */434 "jinja._speedups.BaseContext", /* tp_name */435 sizeof(BaseContext), /* tp_basicsize */436 0, /* tp_itemsize */437 (destructor)BaseContext_dealloc,/* tp_dealloc */438 0, /* tp_print */439 0, /* tp_getattr */440 0, /* tp_setattr */441 0, /* tp_compare */442 0, /* tp_repr */443 0, /* tp_as_number */444 &BaseContext_as_sequence, /* tp_as_sequence */445 &BaseContext_as_mapping, /* tp_as_mapping */446 0, /* tp_hash */447 0, /* tp_call */448 0, /* tp_str */449 0, /* tp_getattro */450 0, /* tp_setattro */451 0, /* tp_as_buffer */452 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,453 /*tp_flags*/454 "", /* tp_doc */455 (traverseproc)BaseContext_traverse, /* tp_traverse */456 (inquiry)BaseContext_clear, /* tp_clear */457 0, /* tp_richcompare */458 0, /* tp_weaklistoffset */459 0, /* tp_iter */460 0, /* tp_iternext */461 BaseContext_methods, /* tp_methods */462 0, /* tp_members */463 BaseContext_getsetters, /* tp_getset */464 0, /* tp_base */465 0, /* tp_dict */466 0, /* tp_descr_get */467 0, /* tp_descr_set */468 0, /* tp_dictoffset */469 (initproc)BaseContext_init, /* tp_init */470 0, /* tp_alloc */471 0 /* tp_new */472};473474static PyMethodDef module_methods[] = {475 {NULL, NULL, 0, NULL} /* Sentinel */476};477478#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */479#define PyMODINIT_FUNC void480#endif481PyMODINIT_FUNC482init_speedups(void)483{484 PyObject *module;485486 BaseContextType.tp_new = (newfunc)PyType_GenericNew;487 if (PyType_Ready(&BaseContextType) < 0)488 return;489490 if (!init_constants())491 return;492493 module = Py_InitModule3("_speedups", module_methods, "");494 if (!module)495 return;496497 Py_INCREF(&BaseContextType);498 PyModule_AddObject(module, "BaseContext", (PyObject*)&BaseContextType);499}
added:jinja2/constants.py+32 added
1# -*- coding: utf-8 -*-2"""3 jinja.constants4 ~~~~~~~~~~~~~~~56 Various constants.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213#: list of lorem ipsum words used by the lipsum() helper function14LOREM_IPSUM_WORDS = u'''\15a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at16auctor augue bibendum blandit class commodo condimentum congue consectetuer17consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus18diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend19elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames20faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac21hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum22justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem23luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie24mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non25nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque26penatibus per pharetra phasellus placerat platea porta porttitor posuere27potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus28ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit29sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor30tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices31ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus32viverra volutpat vulputate'''
added:jinja2/datastructure.py+137 added
1# -*- coding: utf-8 -*-2"""3 jinja2.datastructure4 ~~~~~~~~~~~~~~~~~~~~56 Module that helds several data types used in the template engine.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from operator import itemgetter12from jinja.exceptions import TemplateSyntaxError, TemplateRuntimeError131415_missing = object()161718class Token(tuple):19 """20 Token class.21 """22 __slots__ = ()23 lineno, type, value = map(itemgetter, range(3))2425 def __new__(cls, lineno, type, value):26 return tuple.__new__(cls, (lineno, type, value))2728 def __str__(self):29 from jinja.lexer import keywords, reverse_operators30 if self.type in keywords:31 return self.type32 elif self.type in reverse_operators:33 return reverse_operators[self.type]34 return self.value3536 def __repr__(self):37 return 'Token(%r, %r, %r)' % (38 self.lineno,39 self.type,40 self.value41 )424344class TokenStreamIterator(object):45 """46 The iterator for tokenstreams. Iterate over the stream47 until the eof token is reached.48 """4950 def __init__(self, stream):51 self._stream = stream5253 def __iter__(self):54 return self5556 def next(self):57 token = self._stream.current58 if token.type == 'eof':59 self._stream.close()60 raise StopIteration()61 self._stream.next()62 return token636465class TokenStream(object):66 """67 A token stream wraps a generator and supports pushing tokens back.68 It also provides some functions to expect tokens and similar stuff.6970 Important note: Do never push more than one token back to the71 stream. Although the stream object won't stop you72 from doing so, the behavior is undefined. Multiple73 pushed tokens are only used internally!74 """7576 def __init__(self, generator, filename):77 self._next = generator.next78 self._pushed = []79 self.current = Token(1, 'initial', '')80 self.filename = filename81 self.next()8283 def __iter__(self):84 return TokenStreamIterator(self)8586 def lineno(self):87 """The current line number."""88 return self.current.lineno89 lineno = property(lineno, doc=lineno.__doc__)9091 def __nonzero__(self):92 """Are we at the end of the tokenstream?"""93 return bool(self._pushed) or self.current.type != 'eof'9495 eos = property(lambda x: not x.__nonzero__(), doc=__nonzero__.__doc__)9697 def push(self, token):98 """Push a token back to the stream."""99 self._pushed.append(token)100101 def skip(self, n):102 """Got n tokens ahead."""103 for x in xrange(n):104 self.next()105106 def next(self):107 """Go one token ahead."""108 if self._pushed:109 self.current = self._pushed.pop()110 elif self.current.type != 'eof':111 try:112 self.current = self._next()113 except StopIteration:114 self.close()115116 def close(self):117 """Close the stream."""118 self.current = Token(self.current.lineno, 'eof', '')119 self._next = None120121 def expect(self, token_type, token_value=_missing):122 """Expect a given token type and return it"""123 if self.current.type != token_type:124 raise TemplateSyntaxError("expected token %r, got %r" %125 (token_type, self.current.type),126 self.current.lineno,127 self.filename)128 elif token_value is not _missing and \129 self.current.value != token_value:130 raise TemplateSyntaxError("expected %r, got %r" %131 (token_value, self.current.value),132 self.current.lineno,133 self.filename)134 try:135 return self.current136 finally:137 self.next()
added:jinja2/defaults.py+16 added
1# -*- coding: utf-8 -*-2"""3 jinja.defaults4 ~~~~~~~~~~~~~~56 Jinja default filters and tags.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja.filters import FILTERS as DEFAULT_FILTERS12from jinja.tests import TESTS as DEFAULT_TESTS13DEFAULT_NAMESPACE = {}141516__all__ = ['DEFAULT_FILTERS', 'DEFAULT_TESTS', 'DEFAULT_NAMESPACE']
added:jinja2/environment.py+115 added
1# -*- coding: utf-8 -*-2"""3 jinja.environment4 ~~~~~~~~~~~~~~~~~56 Provides a class that holds runtime and parsing time options.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja.lexer import Lexer12from jinja.parser import Parser13from jinja.loaders import LoaderWrapper14from jinja.datastructure import SilentUndefined, Markup, Context, FakeTranslator15from jinja.utils import collect_translations, get_attribute16from jinja.exceptions import FilterNotFound, TestNotFound, \17 SecurityException, TemplateSyntaxError18from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE192021__all__ = ['Environment']222324#: minor speedup25_getattr = getattr262728class Environment(object):29 """30 The Jinja environment.3132 The core component of Jinja is the `Environment`. It contains33 important shared variables like configuration, filters, tests,34 globals and others.35 """3637 def __init__(self,38 block_start_string='{%',39 block_end_string='%}',40 variable_start_string='{{',41 variable_end_string='}}',42 comment_start_string='{#',43 comment_end_string='#}',44 trim_blocks=False,45 loader=None):46 """47 Here the possible initialization parameters:4849 ========================= ============================================50 `block_start_string` the string marking the begin of a block.51 this defaults to ``'{%'``.52 `block_end_string` the string marking the end of a block.53 defaults to ``'%}'``.54 `variable_start_string` the string marking the begin of a print55 statement. defaults to ``'{{'``.56 `comment_start_string` the string marking the begin of a57 comment. defaults to ``'{#'``.58 `comment_end_string` the string marking the end of a comment.59 defaults to ``'#}'``.60 `trim_blocks` If this is set to ``True`` the first newline61 after a block is removed (block, not62 variable tag!). Defaults to ``False``.63 `loader` The loader for this environment.64 ========================= ============================================65 """6667 # lexer / parser information68 self.block_start_string = block_start_string69 self.block_end_string = block_end_string70 self.variable_start_string = variable_start_string71 self.variable_end_string = variable_end_string72 self.comment_start_string = comment_start_string73 self.comment_end_string = comment_end_string74 self.trim_blocks = trim_blocks7576 # other stuff77 self.template_charset = template_charset78 self.loader = loader7980 # defaults81 self.filters = DEFAULT_FILTERS.copy()82 self.tests = DEFAULT_TESTS.copy()83 self.globals = DEFAULT_NAMESPACE.copy()8485 # create lexer86 self.lexer = Lexer(self)8788 def loader(self, value):89 """90 Get or set the template loader.91 """92 self._loader = LoaderWrapper(self, value)93 loader = property(lambda s: s._loader, loader, doc=loader.__doc__)9495 def parse(self, source, filename=None):96 """97 Parse the sourcecode and return the abstract syntax tree. This tree98 of nodes is used by the `translators`_ to convert the template into99 executable source- or bytecode.100101 .. _translators: translators.txt102 """103 parser = Parser(self, source, filename)104 return parser.parse()105106 def lex(self, source, filename=None):107 """108 Lex the given sourcecode and return a generator that yields tokens.109 The stream returned is not usable for Jinja but can be used if110 Jinja templates should be processed by other tools (for example111 syntax highlighting etc)112113 The tuples are returned in the form ``(lineno, token, value)``.114 """115 return self.lexer.tokeniter(source, filename)
added:jinja2/exceptions.py+42 added
1# -*- coding: utf-8 -*-2"""3 jinja.exceptions4 ~~~~~~~~~~~~~~~~56 Jinja exceptions.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213class TemplateError(RuntimeError):14 pass151617class TemplateNotFound(IOError, LookupError, TemplateError):18 """19 Raised if a template does not exist.20 """2122 def __init__(self, name):23 IOError.__init__(self, name)24 self.name = name252627class TemplateSyntaxError(SyntaxError, TemplateError):28 """29 Raised to tell the user that there is a problem with the template.30 """3132 def __init__(self, message, lineno, filename):33 SyntaxError.__init__(self, message)34 self.lineno = lineno35 self.filename = filename363738class TemplateRuntimeError(TemplateError):39 """40 Raised by the template engine if a tag encountered an error when41 rendering.42 """
added:jinja2/filters.py+985 added
1# -*- coding: utf-8 -*-2"""3 jinja.filters4 ~~~~~~~~~~~~~56 Bundled jinja filters.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12from random import choice13try:14 from operator import itemgetter15except ImportError:16 itemgetter = lambda a: lambda b: b[a]17from urllib import urlencode, quote181920_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')212223def stringfilter(f):24 """25 Decorator for filters that just work on unicode objects.26 """27 def decorator(*args):28 def wrapped(env, context, value):29 nargs = list(args)30 for idx, var in enumerate(nargs):31 if isinstance(var, str):32 nargs[idx] = env.to_unicode(var)33 return f(env.to_unicode(value), *nargs)34 return wrapped35 try:36 decorator.__doc__ = f.__doc__37 decorator.__name__ = f.__name__38 except:39 pass40 return decorator414243def simplefilter(f):44 """45 Decorator for simplifying filters. Filter arguments are passed46 to the decorated function without environment and context. The47 source value is the first argument. (like stringfilter but48 without unicode conversion)49 """50 def decorator(*args):51 def wrapped(env, context, value):52 return f(value, *args)53 return wrapped54 try:55 decorator.__doc__ = f.__doc__56 decorator.__name__ = f.__name__57 except:58 pass59 return decorator606162def do_replace(s, old, new, count=None):63 """64 Return a copy of the value with all occurrences of a substring65 replaced with a new one. The first argument is the substring66 that should be replaced, the second is the replacement string.67 If the optional third argument ``count`` is given, only the first68 ``count`` occurrences are replaced:6970 .. sourcecode:: jinja7172 {{ "Hello World"|replace("Hello", "Goodbye") }}73 -> Goodbye World7475 {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}76 -> d'oh, d'oh, aaargh77 """78 if not isinstance(old, basestring) or \79 not isinstance(new, basestring):80 raise FilterArgumentError('the replace filter requires '81 'string replacement arguments')82 if count is None:83 return s.replace(old, new)84 if not isinstance(count, (int, long)):85 raise FilterArgumentError('the count parameter of the '86 'replace filter requires '87 'an integer')88 return s.replace(old, new, count)89do_replace = stringfilter(do_replace)909192def do_upper(s):93 """94 Convert a value to uppercase.95 """96 return s.upper()97do_upper = stringfilter(do_upper)9899100def do_lower(s):101 """102 Convert a value to lowercase.103 """104 return s.lower()105do_lower = stringfilter(do_lower)106107108def do_escape(attribute=False):109 """110 XML escape ``&``, ``<``, and ``>`` in a string of data. If the111 optional parameter is `true` this filter will also convert112 ``"`` to ``&quot;``. This filter is just used if the environment113 was configured with disabled `auto_escape`.114115 This method will have no effect it the value is already escaped.116 """117 #: because filters are cached we can make a local alias to118 #: speed things up a bit119 e = escape120 def wrapped(env, context, s):121 if isinstance(s, TemplateData):122 return s123 elif hasattr(s, '__html__'):124 return s.__html__()125 #: small speedup, do not convert to unicode if we already126 #: have an unicode object.127 if s.__class__ is not unicode:128 s = env.to_unicode(s)129 return e(s, attribute)130 return wrapped131132133def do_xmlattr(autospace=False):134 """135 Create an SGML/XML attribute string based on the items in a dict.136 All values that are neither `none` nor `undefined` are automatically137 escaped:138139 .. sourcecode:: html+jinja140141 <ul{{ {'class': 'my_list', 'missing': None,142 'id': 'list-%d'|format(variable)}|xmlattr }}>143 ...144 </ul>145146 Results in something like this:147148 .. sourcecode:: html149150 <ul class="my_list" id="list-42">151 ...152 </ul>153154 As you can see it automatically prepends a space in front of the item155 if the filter returned something. You can disable this by passing156 `false` as only argument to the filter.157158 *New in Jinja 1.1*159 """160 e = escape161 def wrapped(env, context, d):162 if not hasattr(d, 'iteritems'):163 raise TypeError('a dict is required')164 result = []165 for key, value in d.iteritems():166 if value not in (None, env.undefined_singleton):167 result.append(u'%s="%s"' % (168 e(env.to_unicode(key)),169 e(env.to_unicode(value), True)170 ))171 rv = u' '.join(result)172 if autospace:173 rv = ' ' + rv174 return rv175 return wrapped176177178def do_capitalize(s):179 """180 Capitalize a value. The first character will be uppercase, all others181 lowercase.182 """183 return s.capitalize()184do_capitalize = stringfilter(do_capitalize)185186187def do_title(s):188 """189 Return a titlecased version of the value. I.e. words will start with190 uppercase letters, all remaining characters are lowercase.191 """192 return s.title()193do_title = stringfilter(do_title)194195196def do_dictsort(case_sensitive=False, by='key'):197 """198 Sort a dict and yield (key, value) pairs. Because python dicts are199 unsorted you may want to use this function to order them by either200 key or value:201202 .. sourcecode:: jinja203204 {% for item in mydict|dictsort %}205 sort the dict by key, case insensitive206207 {% for item in mydict|dicsort(true) %}208 sort the dict by key, case sensitive209210 {% for item in mydict|dictsort(false, 'value') %}211 sort the dict by key, case insensitive, sorted212 normally and ordered by value.213 """214 if by == 'key':215 pos = 0216 elif by == 'value':217 pos = 1218 else:219 raise FilterArgumentError('You can only sort by either '220 '"key" or "value"')221 def sort_func(value, env):222 if isinstance(value, basestring):223 value = env.to_unicode(value)224 if not case_sensitive:225 value = value.lower()226 return value227228 def wrapped(env, context, value):229 items = value.items()230 items.sort(lambda a, b: cmp(sort_func(a[pos], env),231 sort_func(b[pos], env)))232 return items233 return wrapped234235236def do_default(default_value=u'', boolean=False):237 """238 If the value is undefined it will return the passed default value,239 otherwise the value of the variable:240241 .. sourcecode:: jinja242243 {{ my_variable|default('my_variable is not defined') }}244245 This will output the value of ``my_variable`` if the variable was246 defined, otherwise ``'my_variable is not defined'``. If you want247 to use default with variables that evaluate to false you have to248 set the second parameter to `true`:249250 .. sourcecode:: jinja251252 {{ ''|default('the string was empty', true) }}253 """254 def wrapped(env, context, value):255 if (boolean and not value) or value in (env.undefined_singleton, None):256 return default_value257 return value258 return wrapped259260261def do_join(d=u''):262 """263 Return a string which is the concatenation of the strings in the264 sequence. The separator between elements is an empty string per265 default, you can define ith with the optional parameter:266267 .. sourcecode:: jinja268269 {{ [1, 2, 3]|join('|') }}270 -> 1|2|3271272 {{ [1, 2, 3]|join }}273 -> 123274 """275 def wrapped(env, context, value):276 return env.to_unicode(d).join([env.to_unicode(x) for x in value])277 return wrapped278279280def do_count():281 """282 Return the length of the value. In case if getting an integer or float283 it will convert it into a string an return the length of the new284 string. If the object has no length it will of corse return 0.285 """286 def wrapped(env, context, value):287 try:288 if type(value) in (int, float, long):289 return len(str(value))290 return len(value)291 except TypeError:292 return 0293 return wrapped294295296def do_reverse():297 """298 Return a reversed list of the sequence filtered. You can use this299 for example for reverse iteration:300301 .. sourcecode:: jinja302303 {% for item in seq|reverse %}304 {{ item|e }}305 {% endfor %}306 """307 def wrapped(env, context, value):308 try:309 return value[::-1]310 except:311 l = list(value)312 l.reverse()313 return l314 return wrapped315316317def do_center(value, width=80):318 """319 Centers the value in a field of a given width.320 """321 return value.center(width)322do_center = stringfilter(do_center)323324325def do_first():326 """327 Return the frist item of a sequence.328 """329 def wrapped(env, context, seq):330 try:331 return iter(seq).next()332 except StopIteration:333 return env.undefined_singleton334 return wrapped335336337def do_last():338 """339 Return the last item of a sequence.340 """341 def wrapped(env, context, seq):342 try:343 return iter(reversed(seq)).next()344 except StopIteration:345 return env.undefined_singleton346 return wrapped347348349def do_random():350 """351 Return a random item from the sequence.352 """353 def wrapped(env, context, seq):354 try:355 return choice(seq)356 except IndexError:357 return env.undefined_singleton358 return wrapped359360361def do_urlencode():362 """363 urlencode a string or directory.364365 .. sourcecode:: jinja366367 {{ {'foo': 'bar', 'blub': 'blah'}|urlencode }}368 -> foo=bar&blub=blah369370 {{ 'Hello World' }}371 -> Hello%20World372 """373 def wrapped(env, context, value):374 if isinstance(value, dict):375 tmp = {}376 for key, value in value.iteritems():377 key = env.to_unicode(key).encode(env.charset)378 value = env.to_unicode(value).encode(env.charset)379 tmp[key] = value380 return urlencode(tmp)381 else:382 return quote(env.to_unicode(value).encode(env.charset))383 return wrapped384385386def do_jsonencode():387 """388 JSON dump a variable. just works if simplejson is installed.389390 .. sourcecode:: jinja391392 {{ 'Hello World'|jsonencode }}393 -> "Hello World"394 """395 global simplejson396 try:397 simplejson398 except NameError:399 import simplejson400 return lambda e, c, v: simplejson.dumps(v)401402403def do_filesizeformat():404 """405 Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102406 bytes, etc).407 """408 def wrapped(env, context, value):409 # fail silently410 try:411 bytes = float(value)412 except TypeError:413 bytes = 0414415 if bytes < 1024:416 return "%d Byte%s" % (bytes, bytes != 1 and 's' or '')417 elif bytes < 1024 * 1024:418 return "%.1f KB" % (bytes / 1024)419 elif bytes < 1024 * 1024 * 1024:420 return "%.1f MB" % (bytes / (1024 * 1024))421 return "%.1f GB" % (bytes / (1024 * 1024 * 1024))422 return wrapped423424425def do_pprint(verbose=False):426 """427 Pretty print a variable. Useful for debugging.428429 With Jinja 1.2 onwards you can pass it a parameter. If this parameter430 is truthy the output will be more verbose (this requires `pretty`)431 """432 def wrapped(env, context, value):433 return pformat(value, verbose=verbose)434 return wrapped435436437def do_urlize(value, trim_url_limit=None, nofollow=False):438 """439 Converts URLs in plain text into clickable links.440441 If you pass the filter an additional integer it will shorten the urls442 to that number. Also a third argument exists that makes the urls443 "nofollow":444445 .. sourcecode:: jinja446447 {{ mytext|urlize(40, True) }}448 links are shortened to 40 chars and defined with rel="nofollow"449 """450 return urlize(value, trim_url_limit, nofollow)451do_urlize = stringfilter(do_urlize)452453454def do_indent(s, width=4, indentfirst=False):455 """456 {{ s|indent[ width[ indentfirst[ usetab]]] }}457458 Return a copy of the passed string, each line indented by459 4 spaces. The first line is not indented. If you want to460 change the number of spaces or indent the first line too461 you can pass additional parameters to the filter:462463 .. sourcecode:: jinja464465 {{ mytext|indent(2, True) }}466 indent by two spaces and indent the first line too.467 """468 indention = ' ' * width469 if indentfirst:470 return u'\n'.join([indention + line for line in s.splitlines()])471 return s.replace('\n', '\n' + indention)472do_indent = stringfilter(do_indent)473474475def do_truncate(s, length=255, killwords=False, end='...'):476 """477 Return a truncated copy of the string. The length is specified478 with the first parameter which defaults to ``255``. If the second479 parameter is ``true`` the filter will cut the text at length. Otherwise480 it will try to save the last word. If the text was in fact481 truncated it will append an ellipsis sign (``"..."``). If you want a482 different ellipsis sign than ``"..."`` you can specify it using the483 third parameter.484485 .. sourcecode jinja::486487 {{ mytext|truncate(300, false, '&raquo;') }}488 truncate mytext to 300 chars, don't split up words, use a489 right pointing double arrow as ellipsis sign.490 """491 if len(s) <= length:492 return s493 elif killwords:494 return s[:length] + end495 words = s.split(' ')496 result = []497 m = 0498 for word in words:499 m += len(word) + 1500 if m > length:501 break502 result.append(word)503 result.append(end)504 return u' '.join(result)505do_truncate = stringfilter(do_truncate)506507508def do_wordwrap(s, pos=79, hard=False):509 """510 Return a copy of the string passed to the filter wrapped after511 ``79`` characters. You can override this default using the first512 parameter. If you set the second parameter to `true` Jinja will513 also split words apart (usually a bad idea because it makes514 reading hard).515 """516 if len(s) < pos:517 return s518 if hard:519 return u'\n'.join([s[idx:idx + pos] for idx in520 xrange(0, len(s), pos)])521 # code from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061522 return reduce(lambda line, word, pos=pos: u'%s%s%s' %523 (line, u' \n'[(len(line)-line.rfind('\n') - 1 +524 len(word.split('\n', 1)[0]) >= pos)],525 word), s.split(' '))526do_wordwrap = stringfilter(do_wordwrap)527528529def do_wordcount(s):530 """531 Count the words in that string.532 """533 return len([x for x in s.split() if x])534do_wordcount = stringfilter(do_wordcount)535536537def do_textile(s):538 """539 Prase the string using textile.540541 requires the `PyTextile`_ library.542543 .. _PyTextile: http://dealmeida.net/projects/textile/544 """545 from textile import textile546 return textile(s.encode('utf-8')).decode('utf-8')547do_textile = stringfilter(do_textile)548549550def do_markdown(s):551 """552 Parse the string using markdown.553554 requires the `Python-markdown`_ library.555556 .. _Python-markdown: http://www.freewisdom.org/projects/python-markdown/557 """558 from markdown import markdown559 return markdown(s.encode('utf-8')).decode('utf-8')560do_markdown = stringfilter(do_markdown)561562563def do_rst(s):564 """565 Parse the string using the reStructuredText parser from the566 docutils package.567568 requires `docutils`_.569570 .. _docutils: http://docutils.sourceforge.net/571 """572 from docutils.core import publish_parts573 parts = publish_parts(source=s, writer_name='html4css1')574 return parts['fragment']575do_rst = stringfilter(do_rst)576577578def do_int(default=0):579 """580 Convert the value into an integer. If the581 conversion doesn't work it will return ``0``. You can582 override this default using the first parameter.583 """584 def wrapped(env, context, value):585 try:586 return int(value)587 except (TypeError, ValueError):588 try:589 return int(float(value))590 except (TypeError, ValueError):591 return default592 return wrapped593594595def do_float(default=0.0):596 """597 Convert the value into a floating point number. If the598 conversion doesn't work it will return ``0.0``. You can599 override this default using the first parameter.600 """601 def wrapped(env, context, value):602 try:603 return float(value)604 except (TypeError, ValueError):605 return default606 return wrapped607608609def do_string():610 """611 Convert the value into an string.612 """613 return lambda e, c, v: e.to_unicode(v)614615616def do_format(*args):617 """618 Apply python string formatting on an object:619620 .. sourcecode:: jinja621622 {{ "%s - %s"|format("Hello?", "Foo!") }}623 -> Hello? - Foo!624625 Note that you cannot use the mapping syntax (``%(name)s``)626 like in python. Use `|dformat` for that.627 """628 def wrapped(env, context, value):629 return env.to_unicode(value) % args630 return wrapped631632633def do_dformat(d):634 """635 Apply python mapping string formatting on an object:636637 .. sourcecode:: jinja638639 {{ "Hello %(username)s!"|dformat({'username': 'John Doe'}) }}640 -> Hello John Doe!641642 This is useful when adding variables to translateable643 string expressions.644645 *New in Jinja 1.1*646 """647 if not isinstance(d, dict):648 raise FilterArgumentError('dict required')649 def wrapped(env, context, value):650 return env.to_unicode(value) % d651 return wrapped652653654def do_trim(value):655 """656 Strip leading and trailing whitespace.657 """658 return value.strip()659do_trim = stringfilter(do_trim)660661662def do_capture(name='captured', clean=False):663 """664 Store the value in a variable called ``captured`` or a variable665 with the name provided. Useful for filter blocks:666667 .. sourcecode:: jinja668669 {% filter capture('foo') %}670 ...671 {% endfilter %}672 {{ foo }}673674 This will output "..." two times. One time from the filter block675 and one time from the variable. If you don't want the filter to676 output something you can use it in `clean` mode:677678 .. sourcecode:: jinja679680 {% filter capture('foo', True) %}681 ...682 {% endfilter %}683 {{ foo }}684 """685 if not isinstance(name, basestring):686 raise FilterArgumentError('You can only capture into variables')687 def wrapped(env, context, value):688 context[name] = value689 if clean:690 return TemplateData()691 return value692 return wrapped693694695def do_striptags(value):696 """697 Strip SGML/XML tags and replace adjacent whitespace by one space.698699 *new in Jinja 1.1*700 """701 return ' '.join(_striptags_re.sub('', value).split())702do_striptags = stringfilter(do_striptags)703704705def do_slice(slices, fill_with=None):706 """707 Slice an iterator and return a list of lists containing708 those items. Useful if you want to create a div containing709 three div tags that represent columns:710711 .. sourcecode:: html+jinja712713 <div class="columwrapper">714 {%- for column in items|slice(3) %}715 <ul class="column-{{ loop.index }}">716 {%- for item in column %}717 <li>{{ item }}</li>718 {%- endfor %}719 </ul>720 {%- endfor %}721 </div>722723 If you pass it a second argument it's used to fill missing724 values on the last iteration.725726 *new in Jinja 1.1*727 """728 def wrapped(env, context, value):729 result = []730 seq = list(value)731 length = len(seq)732 items_per_slice = length // slices733 slices_with_extra = length % slices734 offset = 0735 for slice_number in xrange(slices):736 start = offset + slice_number * items_per_slice737 if slice_number < slices_with_extra:738 offset += 1739 end = offset + (slice_number + 1) * items_per_slice740 tmp = seq[start:end]741 if fill_with is not None and slice_number >= slices_with_extra:742 tmp.append(fill_with)743 result.append(tmp)744 return result745 return wrapped746747748def do_batch(linecount, fill_with=None):749 """750 A filter that batches items. It works pretty much like `slice`751 just the other way round. It returns a list of lists with the752 given number of items. If you provide a second parameter this753 is used to fill missing items. See this example:754755 .. sourcecode:: html+jinja756757 <table>758 {%- for row in items|batch(3, '&nbsp;') %}759 <tr>760 {%- for column in row %}761 <tr>{{ column }}</td>762 {%- endfor %}763 </tr>764 {%- endfor %}765 </table>766767 *new in Jinja 1.1*768 """769 def wrapped(env, context, value):770 result = []771 tmp = []772 for item in value:773 if len(tmp) == linecount:774 result.append(tmp)775 tmp = []776 tmp.append(item)777 if tmp:778 if fill_with is not None and len(tmp) < linecount:779 tmp += [fill_with] * (linecount - len(tmp))780 result.append(tmp)781 return result782 return wrapped783784785def do_sum():786 """787 Sum up the given sequence of numbers.788789 *new in Jinja 1.1*790 """791 def wrapped(env, context, value):792 return sum(value)793 return wrapped794795796def do_abs():797 """798 Return the absolute value of a number.799800 *new in Jinja 1.1*801 """802 def wrapped(env, context, value):803 return abs(value)804 return wrapped805806807def do_round(precision=0, method='common'):808 """809 Round the number to a given precision. The first810 parameter specifies the precision (default is ``0``), the811 second the rounding method:812813 - ``'common'`` rounds either up or down814 - ``'ceil'`` always rounds up815 - ``'floor'`` always rounds down816817 If you don't specify a method ``'common'`` is used.818819 .. sourcecode:: jinja820821 {{ 42.55|round }}822 -> 43823 {{ 42.55|round(1, 'floor') }}824 -> 42.5825826 *new in Jinja 1.1*827 """828 if not method in ('common', 'ceil', 'floor'):829 raise FilterArgumentError('method must be common, ceil or floor')830 if precision < 0:831 raise FilterArgumentError('precision must be a postive integer '832 'or zero.')833 def wrapped(env, context, value):834 if method == 'common':835 return round(value, precision)836 import math837 func = getattr(math, method)838 if precision:839 return func(value * 10 * precision) / (10 * precision)840 else:841 return func(value)842 return wrapped843844845def do_sort(reverse=False):846 """847 Sort a sequence. Per default it sorts ascending, if you pass it848 `True` as first argument it will reverse the sorting.849850 *new in Jinja 1.1*851 """852 def wrapped(env, context, value):853 return sorted(value, reverse=reverse)854 return wrapped855856857def do_groupby(attribute):858 """859 Group a sequence of objects by a common attribute.860861 If you for example have a list of dicts or objects that represent persons862 with `gender`, `first_name` and `last_name` attributes and you want to863 group all users by genders you can do something like the following864 snippet:865866 .. sourcecode:: html+jinja867868 <ul>869 {% for group in persons|groupby('gender') %}870 <li>{{ group.grouper }}<ul>871 {% for person in group.list %}872 <li>{{ person.first_name }} {{ person.last_name }}</li>873 {% endfor %}</ul></li>874 {% endfor %}875 </ul>876877 As you can see the item we're grouping by is stored in the `grouper`878 attribute and the `list` contains all the objects that have this grouper879 in common.880881 *New in Jinja 1.2*882 """883 def wrapped(env, context, value):884 expr = lambda x: env.get_attribute(x, attribute)885 return sorted([{886 'grouper': a,887 'list': list(b)888 } for a, b in groupby(sorted(value, key=expr), expr)],889 key=itemgetter('grouper'))890 return wrapped891892893def do_getattribute(attribute):894 """895 Get one attribute from an object. Normally you don't have to use this896 filter because the attribute and subscript expressions try to either897 get an attribute of an object or an item. In some situations it could898 be that there is an item *and* an attribute with the same name. In that899 situation only the item is returned, never the attribute.900901 .. sourcecode:: jinja902903 {{ foo.bar }} -> {{ foo|getattribute('bar') }}904905 *New in Jinja 1.2*906 """907 def wrapped(env, context, value):908 try:909 return get_attribute(value, attribute)910 except (SecurityException, AttributeError):911 return env.undefined_singleton912 return wrapped913914915def do_getitem(key):916 """917 This filter basically works like the normal subscript expression but918 it doesn't fall back to attribute lookup. If an item does not exist for919 an object undefined is returned.920921 .. sourcecode:: jinja922923 {{ foo.bar }} -> {{ foo|getitem('bar') }}924925 *New in Jinja 1.2*926 """927 def wrapped(env, context, value):928 try:929 return value[key]930 except (TypeError, KeyError, IndexError, AttributeError):931 return env.undefined_singleton932 return wrapped933934935FILTERS = {936 'replace': do_replace,937 'upper': do_upper,938 'lower': do_lower,939 'escape': do_escape,940 'e': do_escape,941 'xmlattr': do_xmlattr,942 'capitalize': do_capitalize,943 'title': do_title,944 'default': do_default,945 'join': do_join,946 'count': do_count,947 'dictsort': do_dictsort,948 'length': do_count,949 'reverse': do_reverse,950 'center': do_center,951 'title': do_title,952 'capitalize': do_capitalize,953 'first': do_first,954 'last': do_last,955 'random': do_random,956 'urlencode': do_urlencode,957 'jsonencode': do_jsonencode,958 'filesizeformat': do_filesizeformat,959 'pprint': do_pprint,960 'indent': do_indent,961 'truncate': do_truncate,962 'wordwrap': do_wordwrap,963 'wordcount': do_wordcount,964 'textile': do_textile,965 'markdown': do_markdown,966 'rst': do_rst,967 'int': do_int,968 'float': do_float,969 'string': do_string,970 'urlize': do_urlize,971 'format': do_format,972 'dformat': do_dformat,973 'capture': do_capture,974 'trim': do_trim,975 'striptags': do_striptags,976 'slice': do_slice,977 'batch': do_batch,978 'sum': do_sum,979 'abs': do_abs,980 'round': do_round,981 'sort': do_sort,982 'groupby': do_groupby,983 'getattribute': do_getattribute,984 'getitem': do_getitem985}
added:jinja2/lexer.py+503 added
1# -*- coding: utf-8 -*-2"""3 jinja2.lexer4 ~~~~~~~~~~~~56 This module implements a Jinja / Python combination lexer. The7 `Lexer` class provided by this module is used to do some preprocessing8 for Jinja.910 On the one hand it filters out invalid operators like the bitshift11 operators we don't allow in templates. On the other hand it separates12 template code and python code in expressions.1314 :copyright: 2007-2008 by Armin Ronacher.15 :license: BSD, see LICENSE for more details.16"""17import re18import unicodedata19from jinja.datastructure import TokenStream, Token20from jinja.exceptions import TemplateSyntaxError21from weakref import WeakValueDictionary222324__all__ = ['Lexer', 'Failure', 'keywords']252627# cache for the lexers. Exists in order to be able to have multiple28# environments with the same lexer29_lexer_cache = WeakValueDictionary()303132# static regular expressions33whitespace_re = re.compile(r'\s+(?um)')34string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"35 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')36integer_re = re.compile(r'\d+')37name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')38float_re = re.compile(r'\d+\.\d+')394041# set of used keywords42keywords = set(['and', 'block', 'elif', 'else', 'endblock',43 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',44 'endtrans', 'extends', 'filter', 'for', 'if', 'in',45 'include', 'is', 'macro', 'not', 'or', 'pluralize', 'raw',46 'recursive', 'set', 'trans', 'call', 'endcall',47 'true', 'false', 'none'])4849# bind operators to token types50operators = {51 '+': 'add',52 '-': 'sub',53 '/': 'div',54 '//': 'floordiv',55 '*': 'mul',56 '%': 'mod',57 '**': 'pow',58 '~': 'tilde',59 '[': 'lbracket',60 ']': 'rbracket',61 '(': 'lparen',62 ')': 'rparen',63 '{': 'lbrace',64 '}': 'rbrace',65 '==': 'eq',66 '!=': 'ne',67 '>': 'gt',68 '>=': 'gteq',69 '<': 'lt',70 '<=': 'lteq',71 '=': 'assign',72 '.': 'dot',73 ':': 'colon',74 '|': 'pipe',75 ',': 'comma',76 ';': 'semicolon'77}7879reverse_operators = dict([(v, k) for k, v in operators.iteritems()])80assert len(operators) == len(reverse_operators), 'operators dropped'81operator_re = re.compile('(%s)' % '|'.join([re.escape(x) for x in82 sorted(operators, key=lambda x: -len(x))]))8384simple_escapes = {85 'a': '\a',86 'n': '\n',87 'r': '\r',88 'f': '\f',89 't': '\t',90 'v': '\v',91 '\\': '\\',92 '"': '"',93 "'": "'",94 '0': '\x00'95}96unicode_escapes = {97 'x': 2,98 'u': 4,99 'U': 8100}101102103def unescape_string(lineno, filename, s):104 r"""105 Unescape a string. Supported escapes:106 \a, \n, \r\, \f, \v, \\, \", \', \0107108 \x00, \u0000, \U00000000, \N{...}109110 Not supported are \101 because imho redundant.111 """112 result = []113 write = result.append114 chariter = iter(s)115 next_char = chariter.next116117 # faster lookup118 sescapes = simple_escapes119 uescapes = unicode_escapes120121 try:122 for char in chariter:123 if char == '\\':124 char = next_char()125 if char in sescapes:126 write(sescapes[char])127 elif char in uescapes:128 seq = [next_char() for x in xrange(uescapes[char])]129 try:130 write(unichr(int(''.join(seq), 16)))131 except ValueError:132 raise TemplateSyntaxError('invalid unicode codepoint',133 lineno, filename)134 elif char == 'N':135 if next_char() != '{':136 raise TemplateSyntaxError('no name for codepoint',137 lineno, filename)138 seq = []139 while 1:140 char = next_char()141 if char == '}':142 break143 seq.append(char)144 try:145 write(unicodedata.lookup(u''.join(seq)))146 except KeyError:147 raise TemplateSyntaxError('unknown character name',148 lineno, filename)149 else:150 write('\\' + char)151 else:152 write(char)153 except StopIteration:154 raise TemplateSyntaxError('invalid string escape', lineno, filename)155 return u''.join(result)156157158def unescape_regex(s):159 """160 Unescape rules for regular expressions.161 """162 buffer = []163 write = buffer.append164 in_escape = False165 for char in s:166 if in_escape:167 in_escape = False168 if char not in safe_chars:169 write('\\' + char)170 continue171 write(char)172 return u''.join(buffer)173174175class Failure(object):176 """177 Class that raises a `TemplateSyntaxError` if called.178 Used by the `Lexer` to specify known errors.179 """180181 def __init__(self, message, cls=TemplateSyntaxError):182 self.message = message183 self.error_class = cls184185 def __call__(self, lineno, filename):186 raise self.error_class(self.message, lineno, filename)187188189class LexerMeta(type):190 """191 Metaclass for the lexer that caches instances for192 the same configuration in a weak value dictionary.193 """194195 def __call__(cls, environment):196 key = hash((environment.block_start_string,197 environment.block_end_string,198 environment.variable_start_string,199 environment.variable_end_string,200 environment.comment_start_string,201 environment.comment_end_string,202 environment.trim_blocks))203204 # use the cached lexer if possible205 if key in _lexer_cache:206 return _lexer_cache[key]207208 # create a new lexer and cache it209 lexer = type.__call__(cls, environment)210 _lexer_cache[key] = lexer211 return lexer212213214class Lexer(object):215 """216 Class that implements a lexer for a given environment. Automatically217 created by the environment class, usually you don't have to do that.218219 Note that the lexer is not automatically bound to an environment.220 Multiple environments can share the same lexer.221 """222223 __metaclass__ = LexerMeta224225 def __init__(self, environment):226 # shortcuts227 c = lambda x: re.compile(x, re.M | re.S)228 e = re.escape229230 # lexing rules for tags231 tag_rules = [232 (whitespace_re, None, None),233 (float_re, 'float', None),234 (integer_re, 'integer', None),235 ('%s' % '|'.join(sorted(keywords, key=lambda x: -len(x))),236 'keyword', None),237 (name_re, 'name', None),238 (string_re, 'string', None),239 (operator_re, 'operator', None)240 ]241242 #: if variables and blocks have the same delimiters we won't243 #: receive any variable blocks in the parser. This variable is `True`244 #: if we need that.245 self.no_variable_block = (246 (environment.variable_start_string is247 environment.variable_end_string is None) or248 (environment.variable_start_string ==249 environment.block_start_string and250 environment.variable_end_string ==251 environment.block_end_string)252 )253254 # assamble the root lexing rule. because "|" is ungreedy255 # we have to sort by length so that the lexer continues working256 # as expected when we have parsing rules like <% for block and257 # <%= for variables. (if someone wants asp like syntax)258 # variables are just part of the rules if variable processing259 # is required.260 root_tag_rules = [261 ('comment', environment.comment_start_string),262 ('block', environment.block_start_string)263 ]264 if not self.no_variable_block:265 root_tag_rules.append(('variable',266 environment.variable_start_string))267 root_tag_rules.sort(lambda a, b: cmp(len(b[1]), len(a[1])))268269 # block suffix if trimming is enabled270 block_suffix_re = environment.trim_blocks and '\\n?' or ''271272 # global lexing rules273 self.rules = {274 'root': [275 # directives276 (c('(.*?)(?:%s)' % '|'.join(277 ['(?P<raw_begin>(?:\s*%s\-|%s)\s*raw\s*%s)' % (278 e(environment.block_start_string),279 e(environment.block_start_string),280 e(environment.block_end_string)281 )] + [282 '(?P<%s_begin>\s*%s\-|%s)' % (n, e(r), e(r))283 for n, r in root_tag_rules284 ])), ('data', '#bygroup'), '#bygroup'),285 # data286 (c('.+'), 'data', None)287 ],288 # comments289 'comment_begin': [290 (c(r'(.*?)((?:\-%s\s*|%s)%s)' % (291 e(environment.comment_end_string),292 e(environment.comment_end_string),293 block_suffix_re294 )), ('comment', 'comment_end'), '#pop'),295 (c('(.)'), (Failure('Missing end of comment tag'),), None)296 ],297 # blocks298 'block_begin': [299 (c('(?:\-%s\s*|%s)%s' % (300 e(environment.block_end_string),301 e(environment.block_end_string),302 block_suffix_re303 )), 'block_end', '#pop'),304 ] + tag_rules,305 # raw block306 'raw_begin': [307 (c('(.*?)((?:\s*%s\-|%s)\s*endraw\s*(?:\-%s\s*|%s%s))' % (308 e(environment.block_start_string),309 e(environment.block_start_string),310 e(environment.block_end_string),311 e(environment.block_end_string),312 block_suffix_re313 )), ('data', 'raw_end'), '#pop'),314 (c('(.)'), (Failure('Missing end of raw directive'),), None)315 ]316 }317318 # only add the variable rules to the list if we process variables319 # the variable_end_string variable could be None and break things.320 if not self.no_variable_block:321 self.rules['variable_begin'] = [322 (c('\-%s\s*|%s' % (323 e(environment.variable_end_string),324 e(environment.variable_end_string)325 )), 'variable_end', '#pop')326 ] + tag_rules327328 def tokenize(self, source, filename=None):329 """330 Works like `tokeniter` but returns a tokenstream of tokens and not a331 generator or token tuples. Additionally all token values are already332 converted into types and postprocessed. For example keywords are333 already keyword tokens, not named tokens, comments are removed,334 integers and floats converted, strings unescaped etc.335 """336 def generate():337 for lineno, token, value in self.tokeniter(source, filename):338 if token in ('comment_begin', 'comment', 'comment_end'):339 continue340 elif token == 'data':341 try:342 value = str(value)343 except UnicodeError:344 pass345 elif token == 'keyword':346 token = str(value)347 elif token == 'name':348 value = str(value)349 elif token == 'string':350 value = unescape_string(lineno, filename, value[1:-1])351 try:352 value = str(value)353 except UnicodeError:354 pass355 elif token == 'integer':356 value = int(value)357 elif token == 'float':358 value = float(value)359 elif token == 'operator':360 token = operators[value]361 value = ''362 yield Token(lineno, token, value)363 return TokenStream(generate(), filename)364365 def tokeniter(self, source, filename=None):366 """367 This method tokenizes the text and returns the tokens in a generator.368 Use this method if you just want to tokenize a template. The output369 you get is not compatible with the input the jinja parser wants. The370 parser uses the `tokenize` function with returns a `TokenStream` and371 keywords instead of just names.372 """373 source = '\n'.join(source.splitlines())374 pos = 0375 lineno = 1376 stack = ['root']377 statetokens = self.rules['root']378 source_length = len(source)379380 balancing_stack = []381382 while True:383 # tokenizer loop384 for regex, tokens, new_state in statetokens:385 m = regex.match(source, pos)386 # if no match we try again with the next rule387 if not m:388 continue389390 # we only match blocks and variables if brances / parentheses391 # are balanced. continue parsing with the lower rule which392 # is the operator rule. do this only if the end tags look393 # like operators394 if balancing_stack and \395 tokens in ('variable_end', 'block_end'):396 continue397398 # tuples support more options399 if isinstance(tokens, tuple):400 for idx, token in enumerate(tokens):401 # hidden group402 if token is None:403 g = m.group(idx)404 if g:405 lineno += g.count('\n')406 continue407 # failure group408 elif token.__class__ is Failure:409 raise token(lineno, filename)410 # bygroup is a bit more complex, in that case we411 # yield for the current token the first named412 # group that matched413 elif token == '#bygroup':414 for key, value in m.groupdict().iteritems():415 if value is not None:416 yield lineno, key, value417 lineno += value.count('\n')418 break419 else:420 raise RuntimeError('%r wanted to resolve '421 'the token dynamically'422 ' but no group matched'423 % regex)424 # normal group425 else:426 data = m.group(idx + 1)427 if data:428 yield lineno, token, data429 lineno += data.count('\n')430431 # strings as token just are yielded as it, but just432 # if the data is not empty433 else:434 data = m.group()435 # update brace/parentheses balance436 if tokens == 'operator':437 if data == '{':438 balancing_stack.append('}')439 elif data == '(':440 balancing_stack.append(')')441 elif data == '[':442 balancing_stack.append(']')443 elif data in ('}', ')', ']'):444 if not balancing_stack:445 raise TemplateSyntaxError('unexpected "%s"' %446 data, lineno,447 filename)448 expected_op = balancing_stack.pop()449 if expected_op != data:450 raise TemplateSyntaxError('unexpected "%s", '451 'expected "%s"' %452 (data, expected_op),453 lineno, filename)454 # yield items455 if tokens is not None:456 if data:457 yield lineno, tokens, data458 lineno += data.count('\n')459460 # fetch new position into new variable so that we can check461 # if there is a internal parsing error which would result462 # in an infinite loop463 pos2 = m.end()464465 # handle state changes466 if new_state is not None:467 # remove the uppermost state468 if new_state == '#pop':469 stack.pop()470 # resolve the new state by group checking471 elif new_state == '#bygroup':472 for key, value in m.groupdict().iteritems():473 if value is not None:474 stack.append(key)475 break476 else:477 raise RuntimeError('%r wanted to resolve the '478 'new state dynamically but'479 ' no group matched' %480 regex)481 # direct state name given482 else:483 stack.append(new_state)484 statetokens = self.rules[stack[-1]]485 # we are still at the same position and no stack change.486 # this means a loop without break condition, avoid that and487 # raise error488 elif pos2 == pos:489 raise RuntimeError('%r yielded empty string without '490 'stack change' % regex)491 # publish new function and start again492 pos = pos2493 break494 # if loop terminated without break we havn't found a single match495 # either we are at the end of the file or we have a problem496 else:497 # end of text498 if pos >= source_length:499 return500 # something went wrong501 raise TemplateSyntaxError('unexpected char %r at %d' %502 (source[pos], pos), lineno,503 filename)
added:jinja2/loaders.py+10 added
1# -*- coding: utf-8 -*-2"""3 jinja.loaders4 ~~~~~~~~~~~~~56 Jinja loader classes.78 :copyright: 2007 by Armin Ronacher, Bryan McLemore.9 :license: BSD, see LICENSE for more details.10"""
added:jinja2/nodes.py+494 added
1# -*- coding: utf-8 -*-2"""3 jinja2.nodes4 ~~~~~~~~~~~~56 This module implements additional nodes derived from the ast base node.78 It also provides some node tree helper functions like `in_lineno` and9 `get_nodes` used by the parser and translator in order to normalize10 python and jinja nodes.1112 :copyright: 2007 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14"""15import operator16from itertools import chain, izip17from copy import copy181920_binop_to_func = {21 '*': operator.mul,22 '/': operator.truediv,23 '//': operator.floordiv,24 '**': operator.pow,25 '%': operator.mod,26 '+': operator.add,27 '-': operator.sub28}2930_uaop_to_func = {31 'not': operator.not_,32 '+': operator.pos,33 '-': operator.neg34}353637class Impossible(Exception):38 """39 Raised if the node could not perform a requested action.40 """414243class NodeType(type):4445 def __new__(cls, name, bases, d):46 for attr in '_fields', '_attributes':47 storage = []48 for base in bases:49 storage.extend(getattr(base, attr, ()))50 storage.extend(d.get(attr, ()))51 assert len(storage) == len(set(storage))52 d[attr] = tuple(storage)53 return type.__new__(cls, name, bases, d)545556class Node(object):57 """58 Base jinja node.59 """60 __metaclass__ = NodeType61 _fields = ()62 _attributes = ('lineno',)6364 def __init__(self, *args, **kw):65 if args:66 if len(args) != len(self._fields):67 if not self._fields:68 raise TypeError('%r takes 0 arguments' %69 self.__class__.__name__)70 raise TypeError('%r takes 0 or %d argument%s' % (71 self.__class__.__name__,72 len(self._fields),73 len(self._fields) != 1 and 's' or ''74 ))75 for name, arg in izip(self._fields, args):76 setattr(self, name, arg)77 for attr in self._attributes:78 setattr(self, attr, kw.pop(attr, None))79 if kw:80 raise TypeError('unknown keyword argument %r' %81 iter(kw).next())8283 def iter_fields(self):84 for name in self._fields:85 try:86 yield name, getattr(self, name)87 except AttributeError:88 pass8990 def iter_child_nodes(self):91 for field, item in self.iter_fields():92 if isinstance(item, list):93 for n in item:94 if isinstance(n, Node):95 yield n96 elif isinstance(item, Node):97 yield item9899 def __repr__(self):100 return '%s(%s)' % (101 self.__class__.__name__,102 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for103 arg in self._fields)104 )105106107class Stmt(Node):108 """109 Base node for all statements.110 """111112113class Helper(Node):114 """115 Nodes that exist in a specific context only.116 """117118119class Template(Node):120 """121 Node that represents a template.122 """123 _fields = ('extends', 'body')124125126class Output(Stmt):127 """128 A node that holds multiple expressions which are then printed out. This129 is used both for the `print` statement and the regular template data.130 """131 _fields = ('nodes',)132133134class Extends(Stmt):135 """136 Represents an extends statement.137 """138 _fields = ('extends',)139140141class For(Stmt):142 """143 A node that represents a for loop144 """145 _fields = ('item', 'seq', 'body', 'else_', 'recursive')146147148class If(Stmt):149 """150 A node that represents an if condition.151 """152 _fields = ('test', 'body', 'else_')153154155class Macro(Stmt):156 """157 A node that represents a macro.158 """159 _fields = ('name', 'arguments', 'body')160161162class CallBlock(Stmt):163 """164 A node that represents am extended macro call.165 """166 _fields = ('expr', 'body')167168169class Set(Stmt):170 """171 Allows defining own variables.172 """173 _fields = ('name', 'expr')174175176class FilterBlock(Stmt):177 """178 Node for filter sections.179 """180 _fields = ('body', 'filters')181182183class Block(Stmt):184 """185 A node that represents a block.186 """187 _fields = ('name', 'body')188189190class Include(Stmt):191 """192 A node that represents the include tag.193 """194 _fields = ('template',)195196197class Trans(Stmt):198 """199 A node for translatable sections.200 """201 _fields = ('singular', 'plural', 'indicator', 'replacements')202203204class ExprStmt(Stmt):205 """206 A statement that evaluates an expression to None.207 """208 _fields = ('node',)209210211class Expr(Node):212 """213 Baseclass for all expressions.214 """215216 def as_const(self):217 """218 Return the value of the expression as constant or raise `Impossible`219 if this was not possible.220 """221 raise Impossible()222223 def can_assign(self):224 """225 Check if it's possible to assign something to this node.226 """227 return False228229230class BinExpr(Expr):231 """232 Baseclass for all binary expressions.233 """234 _fields = ('left', 'right')235 operator = None236237 def as_const(self):238 f = _binop_to_func[self.operator]239 try:240 return f(self.left.as_const(), self.right.as_const())241 except:242 print self.left, f, self.right243 raise Impossible()244245246class UnaryExpr(Expr):247 """248 Baseclass for all unary expressions.249 """250 _fields = ('node',)251 operator = None252253 def as_const(self):254 f = _uaop_to_func[self.operator]255 try:256 return f(self.node.as_const())257 except:258 raise Impossible()259260261class Name(Expr):262 """263 any name such as {{ foo }}264 """265 _fields = ('name',)266267 def can_assign(self):268 return True269270271class Literal(Expr):272 """273 Baseclass for literals.274 """275276277class Const(Literal):278 """279 any constat such as {{ "foo" }}280 """281 _fields = ('value',)282283 def as_const(self):284 return self.value285286287class Tuple(Literal):288 """289 For loop unpacking and some other things like multiple arguments290 for subscripts.291 """292 _fields = ('items',)293294 def as_const(self):295 return tuple(x.as_const() for x in self.items)296297 def can_assign(self):298 for item in self.items:299 if not item.can_assign():300 return False301 return True302303304class List(Literal):305 """306 any list literal such as {{ [1, 2, 3] }}307 """308 _fields = ('items',)309310 def as_const(self):311 return [x.as_const() for x in self.items]312313314class Dict(Literal):315 """316 any dict literal such as {{ {1: 2, 3: 4} }}317 """318 _fields = ('items',)319320 def as_const(self):321 return dict(x.as_const() for x in self.items)322323324class Pair(Helper):325 """326 A key, value pair for dicts.327 """328 _fields = ('key', 'value')329330 def as_const(self):331 return self.key.as_const(), self.value.as_const()332333334class CondExpr(Expr):335 """336 {{ foo if bar else baz }}337 """338 _fields = ('test', 'expr1', 'expr2')339340 def as_const(self):341 if self.test.as_const():342 return self.expr1.as_const()343 return self.expr2.as_const()344345346class Filter(Expr):347 """348 {{ foo|bar|baz }}349 """350 _fields = ('node', 'filters')351352353class Test(Expr):354 """355 {{ foo is lower }}356 """357 _fields = ('node', 'name', 'args')358359360class Call(Expr):361 """362 {{ foo(bar) }}363 """364 _fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')365366367class Subscript(Expr):368 """369 {{ foo.bar }} and {{ foo['bar'] }} etc.370 """371 _fields = ('node', 'arg')372373 def as_const(self):374 try:375 return self.node.as_const()[self.node.as_const()]376 except:377 raise Impossible()378379 def can_assign(self):380 return True381382383class Slice(Expr):384 """385 1:2:3 etc.386 """387 _fields = ('start', 'stop', 'step')388389390class Concat(Expr):391 """392 For {{ foo ~ bar }}. Concatenates strings.393 """394 _fields = ('nodes',)395396 def as_const(self):397 return ''.join(unicode(x.as_const()) for x in self.nodes)398399400class Compare(Expr):401 """402 {{ foo == bar }}, {{ foo >= bar }} etc.403 """404 _fields = ('expr', 'ops')405406407class Mul(BinExpr):408 """409 {{ foo * bar }}410 """411 operator = '*'412413414class Div(BinExpr):415 """416 {{ foo / bar }}417 """418 operator = '/'419420421class FloorDiv(BinExpr):422 """423 {{ foo // bar }}424 """425 operator = '//'426427428class Add(BinExpr):429 """430 {{ foo + bar }}431 """432 operator = '+'433434435class Sub(BinExpr):436 """437 {{ foo - bar }}438 """439 operator = '-'440441442class Mod(BinExpr):443 """444 {{ foo % bar }}445 """446 operator = '%'447448449class Pow(BinExpr):450 """451 {{ foo ** bar }}452 """453 operator = '**'454455456class And(BinExpr):457 """458 {{ foo and bar }}459 """460 operator = 'and'461462 def as_const(self):463 return self.left.as_const() and self.right.as_const()464465466class Or(BinExpr):467 """468 {{ foo or bar }}469 """470 operator = 'or'471472 def as_const(self):473 return self.left.as_const() or self.right.as_const()474475476class Not(UnaryExpr):477 """478 {{ not foo }}479 """480 operator = 'not'481482483class NegExpr(UnaryExpr):484 """485 {{ -foo }}486 """487 operator = '-'488489490class PosExpr(UnaryExpr):491 """492 {{ +foo }}493 """494 operator = '+'
added:jinja2/parser.py+39 added
1# -*- coding: utf-8 -*-2"""3 jinja2.parser4 ~~~~~~~~~~~~~56 Implements the template parser.78 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja import nodes12from jinja.exceptions import TemplateSyntaxError131415__all__ = ['Parser']161718class Parser(object):19 """20 The template parser class.2122 Transforms sourcecode into an abstract syntax tree.23 """2425 def __init__(self, environment, source, filename=None):26 self.environment = environment27 if isinstance(source, str):28 source = source.decode(environment.template_charset, 'ignore')29 if isinstance(filename, unicode):30 filename = filename.encode('utf-8')31 self.source = source32 self.filename = filename33 self.closed = False34 self.blocks = set()35 self.no_variable_block = self.environment.lexer.no_variable_block36 self.stream = environment.lexer.tokenize(source, filename)3738 def parse(self):39 pass
added:jinja2/tests.py+143 added
1# -*- coding: utf-8 -*-2"""3 jinja.tests4 ~~~~~~~~~~~56 Jinja test functions. Used with the "is" operator.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re121314number_re = re.compile(r'^-?\d+(\.\d+)?$')15regex_type = type(number_re)161718def test_odd():19 """20 Return true if the variable is odd.21 """22 return lambda e, c, v: v % 2 == 1232425def test_even():26 """27 Return true of the variable is even.28 """29 return lambda e, c, v: v % 2 == 0303132def test_defined():33 """34 Return true if the variable is defined:3536 .. sourcecode:: jinja3738 {% if variable is defined %}39 value of variable: {{ variable }}40 {% else %}41 variable is not defined42 {% endif %}4344 See also the ``default`` filter.45 """46 return lambda e, c, v: v is not e.undefined_singleton474849def test_lower():50 """51 Return true if the variable is lowercase.52 """53 return lambda e, c, v: isinstance(v, basestring) and v.islower()545556def test_upper():57 """58 Return true if the variable is uppercase.59 """60 return lambda e, c, v: isinstance(v, basestring) and v.isupper()616263def test_numeric():64 """65 Return true if the variable is numeric.66 """67 return lambda e, c, v: isinstance(v, (int, long, float)) or (68 isinstance(v, basestring) and69 number_re.match(v) is not None)707172def test_sequence():73 """74 Return true if the variable is a sequence. Sequences are variables75 that are iterable.76 """77 def wrapped(environment, context, value):78 try:79 len(value)80 value.__getitem__81 except:82 return False83 return True84 return wrapped858687def test_matching(regex):88 r"""89 Test if the variable matches the regular expression given. Note that90 you have to escape special chars using *two* backslashes, these are91 *not* raw strings.9293 .. sourcecode:: jinja9495 {% if var is matching @/^\d+$/ %}96 var looks like a number97 {% else %}98 var doesn't really look like a number99 {% endif %}100 """101 def wrapped(environment, context, value):102 if type(regex) is regex_type:103 regex_ = regex104 else:105 if environment.disable_regexps:106 raise RuntimeError('regular expressions disabled.')107 if isinstance(regex, unicode):108 regex_ = re.compile(regex, re.U)109 elif isinstance(regex, str):110 regex_ = re.compile(regex)111 else:112 return False113 return regex_.search(value) is not None114 return wrapped115116117def test_sameas(other):118 """119 Check if an object points to the same memory address than another120 object:121122 .. sourcecode:: jinja123124 {% if foo.attribute is sameas(false) %}125 the foo attribute really is the `False` singleton126 {% endif %}127128 *New in Jinja 1.2*129 """130 return lambda e, c, v: v is other131132133TESTS = {134 'odd': test_odd,135 'even': test_even,136 'defined': test_defined,137 'lower': test_lower,138 'upper': test_upper,139 'numeric': test_numeric,140 'sequence': test_sequence,141 'matching': test_matching,142 'sameas': test_sameas143}
added:jinja2/utils.py+10 added
1# -*- coding: utf-8 -*-2"""3 jinja2.utils4 ~~~~~~~~~~~~56 Utility functions.78 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""