Skip to content
Myr

documentation update

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

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent ed98cac · Browse files · 10 files+328 added−34 removed
This commit

State

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

Diff stats

10 files+328 added−34 removed

  • tests:+3 added−3 removed
  • other:+325 added−31 removed

10 files+328 added−34 removed

modified:docs/_static/style.css+6 added-1 removed
194 unmodified lines
195 background-color: #fafafa;196 border-bottom: 1px solid #eee;197}198199a.reference:hover tt {200 border-bottom-color: #aaa;201}202203cite {204 /* abusing <cite>, it's generated by ReST for `x` */205 font-size: 13px;206 font-family: 'Bitstream Vera Sans Mono', 'Monaco', monospace;
87 unmodified lines
294 color: #000;295}296297dl.function dt,294dl.class dt {298dl.class dt,299dl.exception dt {300 font-weight: normal;301}302303dt .descname {
38 unmodified lines
modified:docs/api.rst+8 added-6 removed
46 unmodified lines
47High Level API48--------------4950.. autoclass:: jinja2.environment.Environment([options])51 :members: from_string, get_template, join_path, parse51 :members: from_string, get_template, join_path, parse, lex5253 .. attribute:: shared5455 If a template was created by using the :class:`Template` constructor
117 unmodified lines
173 blocks registered. The last item in each list is the current active174 block (latest in the inheritance chain).175176177.. _loaders:178179Loaders180-------181182Loaders are responsible for loading templates from a resource such as the
50 unmodified lines
233234Exceptions235----------236235.. autoclass:: jinja2.exceptions.TemplateError237.. autoexception:: jinja2.exceptions.TemplateError238237.. autoclass:: jinja2.exceptions.UndefinedError239.. autoexception:: jinja2.exceptions.UndefinedError240239.. autoclass:: jinja2.exceptions.TemplateNotFound241.. autoexception:: jinja2.exceptions.TemplateNotFound242241.. autoclass:: jinja2.exceptions.TemplateSyntaxError243.. autoexception:: jinja2.exceptions.TemplateSyntaxError244243.. autoclass:: jinja2.exceptions.TemplateAssertionError245.. autoexception:: jinja2.exceptions.TemplateAssertionError246247248.. _writing-filters:249
102 unmodified lines
modified:docs/index.rst+2 added
8 unmodified lines
9 :maxdepth: 21011 intro12 api13 sandbox14 templates15 extensions16 integration17 switching1819 changelog2021If you can't find the information you're looking for, have a look at the
4 unmodified lines
added:docs/sandbox.rst+27 added
1Sandbox2=======34The Jinja2 sandbox can be used to evaluate untrusted code. Access to unsafe5attributes and methods is prohibited.67Assuming `env` is a :class:`SandboxedEnvironment` in the default configuration8the following piece of code shows how it works:910>>> env.from_string("{{ func.func_code }}").render(func=lambda:None)11u''12>>> env.from_string("{{ func.func_code.do_something }}").render(func=lambda:None)13Traceback (most recent call last):14 ...15SecurityError: access to attribute 'func_code' of 'function' object is unsafe.161718.. module:: jinja2.sandbox1920.. autoclass:: SandboxedEnvironment([options])21 :members: is_safe_attribute, is_safe_callable2223.. autoexception:: SecurityError2425.. autofunction:: unsafe2627.. autofunction:: is_internal_attribute
added:docs/switching.rst+217 added
1Switching from other Template Engines2=====================================34.. highlight:: html+jinja56If you have used a different template engine in the past and want to swtich7to Jinja2 here is a small guide that shows the basic syntatic and semantic8changes between some common, similar text template engines for Python.910Jinja111------1213Jinja2 is mostly compatible with Jinja1 in terms of API usage and template14syntax. The differences between Jinja1 and 2 are explained in the following15list.1617API18~~~1920Loaders21 Jinja2 uses a different loader API. Because the internal representation22 of templates changed there is no longer support for external caching23 systems such as memcached. The memory consumed by templates is comparable24 with regular Python modules now and external caching doesn't give any25 advantage. If you have used a custom loader in the past have a look at26 the new :ref:`loader API <loaders>`.2728Loading templates from strings29 In the past it was possible to generate templates from a string with the30 default environment configuration by using `jinja.from_string`. Jinja231 provides a :class:`Template` class that can be used to do the same, but32 with optional additional configuration.3334Automatic unicode conversion35 Jinja1 performed automatic conversion of bytestrings in a given encoding36 into unicode objects. This conversion is no longer implemented as it37 was inconsistent as most libraries are using the regular Python ASCII38 bytestring to Unicode conversion. An application powered by Jinja239 *has to* use unicode internally everywhere or make sure that Jinja2 only40 gets unicode strings passed.4142i18n43 Jinja1 used custom translators for internationalization. i18n is now44 available as Jinja2 extension and uses a simpler, more gettext friendly45 interface and has support for babel. For more details see46 :ref:`i18n-extension`.4748Internal methods49 Jinja1 exposed a few internal methods on the environment object such50 as `call_function`, `get_attribute` and others. While they were marked51 as being an internal method it was possible to override them. Jinja252 doesn't have equivalent methods.5354Sandbox55 Jinja1 was running sandbox mode by default. Few applications actually56 used that feature so it became optional in Jinja2. For more details57 about the sandboxed execution see :class:`SandboxedEnvironment`.5859Context60 Jinja1 had a stacked context as storage for variables passed to the61 environment. In Jinja2 a similar object exists but it doesn't allow62 modifications nor is it a singleton. As inheritance is dynamic now63 multiple context objects may exist during template evaluation.646566Templates67~~~~~~~~~6869Jinja2 has mostly the same syntax as Jinja1. The only difference is that70assigning variables doesn't use `set` as keyword now. The following71example shows a Jinja1 variable assignment::7273 {% set foo = 42 %}7475In Jinja2 the `set` is ommited::7677 {% foo = 42 %}7879Additionally macros require parentheses around the argument list now.8081Jinja2 allows dynamic inheritance now and dynamic includes. The old helper82function `rendertemplate` is gone now, `include` can be used instead.83Additionally includes no longer import macros and variable assignments, for84that the new `import` tag is used. This concept is explained in the85:ref:`import` documentation.8687Currently there is no support for the `recursive` modifier of for loops!888990Django91------9293If you have previously worked with Django templates, you should find94Jinja2 very familiar. In fact, most of the syntax elements look and95work the same.9697However, Jinja2 provides some more syntax elements covered in the98documentation and some work a bit different.99100This section covers the template changes. As the API is fundamentally101different we won't cover it here.102103Method Calls104~~~~~~~~~~~~105106In Django method calls work implicitly. With Jinja2 you have to specify that107you want to call an object. Thus this Django code::108109 {% for page in user.get_created_pages %}110 ...111 {% endfor %}112 113will look like this in Jinja::114115 {% for page in user.get_created_pages() %}116 ...117 {% endfor %}118119This allows you to pass variables to the function which is also used for macros120which is not possible in Django.121122Conditions123~~~~~~~~~~124125In Django you can use the following constructs to check for equality::126127 {% ifequals foo "bar" %}128 ...129 {% else %}130 ...131 {% endifequals %}132133In Jinja2 you can use the normal if statement in combination with operators::134135 {% if foo == 'bar' %}136 ...137 {% else %}138 ...139 {% endif %}140141You can also have multiple elif branches in your template::142143 {% if something %}144 ...145 {% elif otherthing %}146 ...147 {% elif foothing %}148 ...149 {% else %}150 ...151 {% endif %}152153Filter Arguments154~~~~~~~~~~~~~~~~155156Jinja2 provides more than one argument for filters. Also the syntax for157argument passing is different. A template that looks like this in Django::158159 {{ items|join:", " }}160161looks like this in Jinja2::162163 {{ items|join(', ') }}164165In fact it's a bit more verbose but it allows different types of arguments -166including variables - and more than one of them.167168Tests169~~~~~170171In addition to filters there also are tests you can perform using the is172operator. Here are some examples::173174 {% if user.user_id is odd %}175 {{ user.username|e }} is odd176 {% else %}177 hmm. {{ user.username|e }} looks pretty normal178 {% endif %}179180181Mako182----183184.. highlight:: html+mako185186If you have used Mako so far and want to switch to Jinja2 you can configure187Jinja2 to look more like Mako:188189.. sourcecode:: python190191 env = Environment('<%', '%>', '${', '}', '%')192193Once the environment is configure like that Jinja2 should be able to interpret194a small subset of Mako templates. Jinja2 does not support embedded Python code195so you would have to move that out of the template. The syntax for defs (in196Jinja2 defs are called macros) and template inheritance is different too. The197following Mako template::198199 <%inherit file="layout.html" />200 <%def name="title()">Page Title</%def>201 <ul>202 % for item in list:203 <li>${item}</li>204 % endfor205 </ul>206207Looks like this in Jinja2 with the above configuration::208209 <% extends "layout.html" %>210 <% block title %>Page Title<% endblock %>211 <% block body %>212 <ul>213 % for item in list:214 <li>${item}</li>215 % endfor216 </ul>217 <% endblock %>
modified:jinja2/environment.py+4 added-2 removed
291 unmodified lines
292 except TemplateSyntaxError, e:293 exc_type, exc_value, tb = translate_syntax_error(e)294 raise exc_type, exc_value, tb295296 def lex(self, source, name=None):296 def lex(self, source, filename=None):297 """Lex the given sourcecode and return a generator that yields298 tokens as tuples in the form ``(lineno, token_type, value)``.299 This can be useful for :ref:`extension development <writing-extensions>`300 and debugging templates.301 """300 return self.lexer.tokeniter(source, name)302 return self.lexer.tokeniter(source, filename)303304 def compile(self, source, name=None, filename=None, globals=None,305 raw=False):306 """Compile a node or template source code. The `name` parameter is
375 unmodified lines
modified:jinja2/exceptions.py+6 added
16 unmodified lines
17class UndefinedError(TemplateError):18 """Raised if a template tries to operate on :class:`Undefined`."""192021class SecurityError(TemplateError):22 """Raised if a template tries to do something insecure if the23 sandbox is enabled.24 """252627class TemplateNotFound(IOError, LookupError, TemplateError):28 """Raised if a template does not exist."""2930 def __init__(self, name):
29 unmodified lines
modified:jinja2/runtime.py+5 added-3 removed
304 unmodified lines
305 self._undefined_name306 )307 else:308 hint = self._undefined_hint309 raise UndefinedError(hint)309 raise self._undefined_exception(hint)310311312class Undefined(object):313 """The default undefined type. This undefined type can be printed and
8 unmodified lines
322 Traceback (most recent call last):323 ...324 jinja2.exceptions.UndefinedError: 'foo' is undefined325 """326 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name')326 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',327 '_undefined_exception')328328 def __init__(self, hint=None, obj=None, name=None):329 def __init__(self, hint=None, obj=None, name=None, exc=UndefinedError):330 self._undefined_hint = hint331 self._undefined_obj = obj332 self._undefined_name = name333 self._undefined_exception = exc334335 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \336 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \337 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
76 unmodified lines
modified:jinja2/sandbox.py+50 added-19 removed
14 unmodified lines
15from types import FunctionType, MethodType, TracebackType, CodeType, \16 FrameType, GeneratorType17from jinja2.runtime import Undefined18from jinja2.environment import Environment19from jinja2.exceptions import SecurityError202122#: maximum number of items a range may produce23MAX_RANGE = 100000
17 unmodified lines
41 return rng424344def unsafe(f):44 """Mark a function as unsafe."""45 """46 Mark a function or method as unsafe::4748 @unsafe49 def delete(self):50 pass51 """52 f.unsafe_callable = True53 return f545556def is_internal_attribute(obj, attr):57 """Test if the attribute given is an internal python attribute. For58 example this function returns `True` for the `func_code` attribute of59 python objects. This is useful if the environment method60 :meth:`~SandboxedEnvironment.is_safe_attribute` is overriden.6162 >>> from jinja2.sandbox import is_internal_attribute63 >>> is_internal_attribute(lambda: None, "func_code")64 True65 >>> is_internal_attribute((lambda x:x).func_code, 'co_code')66 True67 >>> is_internal_attribute(str, "upper")68 False69 """70 if isinstance(obj, FunctionType):71 return attr in UNSAFE_FUNCTION_ATTRIBUTES72 if isinstance(obj, MethodType):73 return attr in UNSAFE_FUNCTION_ATTRIBUTES or \74 attr in UNSAFE_METHOD_ATTRIBUTES75 if isinstance(obj, type):76 return attr == 'mro'77 if isinstance(obj, (CodeType, TracebackType, FrameType)):78 return True79 if isinstance(obj, GeneratorType):80 return attr == 'gi_frame'81 return attr.startswith('__')828384class SandboxedEnvironment(Environment):50 """The sandboxed environment"""85 """The sandboxed environment. It works like the regular environment but86 tells the compiler to generate sandboxed code. Additionally subclasses of87 this environment may override the methods that tell the runtime what88 attributes or functions are safe to access.8990 If the template tries to access insecure code a :exc:`SecurityError` is91 raised. However also other exceptions may occour during the rendering so92 the caller has to ensure that all exceptions are catched.93 """94 sandboxed = True9596 def __init__(self, *args, **kwargs):97 Environment.__init__(self, *args, **kwargs)
2 unmodified lines
100 def is_safe_attribute(self, obj, attr, value):101 """The sandboxed environment will call this method to check if the102 attribute of an object is safe to access. Per default all attributes103 starting with an underscore are considered private as well as the61 special attributes of functions and methods.104 special attributes of internal python objects as returned by the105 :func:`is_internal_attribute` function.106 """63 if attr.startswith('_'):64 return False65 if isinstance(obj, FunctionType):66 return attr not in UNSAFE_FUNCTION_ATTRIBUTES67 if isinstance(obj, MethodType):68 return attr not in UNSAFE_FUNCTION_ATTRIBUTES and \69 attr not in UNSAFE_METHOD_ATTRIBUTES70 if isinstance(obj, type):71 return attr != 'mro'72 if isinstance(obj, (CodeType, TracebackType, FrameType)):73 return False74 if isinstance(obj, GeneratorType):75 return attr != 'gi_frame'76 return True107 return not (attr.startswith('_') or is_internal_attribute(obj, attr))108109 def is_safe_callable(self, obj):110 """Check if an object is safely callable. Per default a function is111 considered safe unless the `unsafe_callable` attribute exists and is
21 unmodified lines
133 return self.undefined('access to attribute %r of %r object is'134 ' unsafe.' % (135 argument,136 obj.__class__.__name__106 ), name=argument)137 ), name=argument, exc=SecurityError)138 return self.undefined(obj=obj, name=argument)139140 def call(__self, __obj, *args, **kwargs):141 """Call an object from sandboxed code."""142 # the double prefixes are to avoid double keyword argument143 # errors when proxying the call.144 if not __self.is_safe_callable(__obj):114 raise TypeError('%r is not safely callable' % (__obj,))145 raise SecurityError('%r is not safely callable' % (__obj,))146 return __obj(*args, **kwargs)
modified:tests/test_security.py+3 added-3 removed
33 unmodified lines
34>>> env = MODULE.SandboxedEnvironment()35>>> env.from_string("{{ foo.foo() }}").render(foo=MODULE.PrivateStuff())36Traceback (most recent call last):37 ...38TypeError: <bound method PrivateStuff.foo of PrivateStuff> is not safely callable38SecurityError: <bound method PrivateStuff.foo of PrivateStuff> is not safely callable39>>> env.from_string("{{ foo.bar() }}").render(foo=MODULE.PrivateStuff())40u'23'4142>>> env.from_string("{{ foo._foo() }}").render(foo=MODULE.PublicStuff())43Traceback (most recent call last):44 ...45UndefinedError: access to attribute '_foo' of 'PublicStuff' object is unsafe.45SecurityError: access to attribute '_foo' of 'PublicStuff' object is unsafe.46>>> env.from_string("{{ foo.bar() }}").render(foo=MODULE.PublicStuff())47u'23'4849>>> env.from_string("{{ foo.__class__ }}").render(foo=42)
2 unmodified lines
52u''53>>> env.from_string("{{ foo.__class__.__subclasses__() }}").render(foo=42)54Traceback (most recent call last):55 ...56UndefinedError: access to attribute '__class__' of 'int' object is unsafe.56SecurityError: access to attribute '__class__' of 'int' object is unsafe.57'''585960test_restricted = '''
10 unmodified lines