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
Provenance
- Commit
5cdc1ac- Tree
53e4306- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
ed98cac
10 files changed+328 added−34 removed
modified:docs/_static/style.css+6 added-1 removed
194 unmodified lines195 background-color: #fafafa;196 border-bottom: 1px solid #eee;197 }198 199+a.reference:hover tt {200+ border-bottom-color: #aaa;201+}202+203 cite {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 lines294 color: #000;295 }296 297 dl.function dt,294-dl.class dt {298+dl.class dt,299+dl.exception dt {300 font-weight: normal;301 }302 303 dt .descname {38 unmodified linesmodified:docs/api.rst+8 added-6 removed
46 unmodified lines47 High Level API48 --------------49 50 .. autoclass:: jinja2.environment.Environment([options])51- :members: from_string, get_template, join_path, parse51+ :members: from_string, get_template, join_path, parse, lex52 53 .. attribute:: shared54 55 If a template was created by using the :class:`Template` constructor117 unmodified lines173 blocks registered. The last item in each list is the current active174 block (latest in the inheritance chain).175 176 177+.. _loaders:178+179 Loaders180 -------181 182 Loaders are responsible for loading templates from a resource such as the50 unmodified lines233 234 Exceptions235 ----------236 235-.. autoclass:: jinja2.exceptions.TemplateError237+.. autoexception:: jinja2.exceptions.TemplateError238 237-.. autoclass:: jinja2.exceptions.UndefinedError239+.. autoexception:: jinja2.exceptions.UndefinedError240 239-.. autoclass:: jinja2.exceptions.TemplateNotFound241+.. autoexception:: jinja2.exceptions.TemplateNotFound242 241-.. autoclass:: jinja2.exceptions.TemplateSyntaxError243+.. autoexception:: jinja2.exceptions.TemplateSyntaxError244 243-.. autoclass:: jinja2.exceptions.TemplateAssertionError245+.. autoexception:: jinja2.exceptions.TemplateAssertionError246 247 248 .. _writing-filters:249 102 unmodified linesmodified:docs/index.rst+2 added
8 unmodified lines9 :maxdepth: 210 11 intro12 api13+ sandbox14 templates15 extensions16 integration17+ switching18 19 changelog20 21 If you can't find the information you're looking for, have a look at the4 unmodified linesadded:docs/sandbox.rst+27 added
1+Sandbox2+=======3+4+The Jinja2 sandbox can be used to evaluate untrusted code. Access to unsafe5+attributes and methods is prohibited.6+7+Assuming `env` is a :class:`SandboxedEnvironment` in the default configuration8+the following piece of code shows how it works:9+10+>>> env.from_string("{{ func.func_code }}").render(func=lambda:None)11+u''12+>>> env.from_string("{{ func.func_code.do_something }}").render(func=lambda:None)13+Traceback (most recent call last):14+ ...15+SecurityError: access to attribute 'func_code' of 'function' object is unsafe.16+17+18+.. module:: jinja2.sandbox19+20+.. autoclass:: SandboxedEnvironment([options])21+ :members: is_safe_attribute, is_safe_callable22+23+.. autoexception:: SecurityError24+25+.. autofunction:: unsafe26+27+.. autofunction:: is_internal_attributeadded:docs/switching.rst+217 added
1+Switching from other Template Engines2+=====================================3+4+.. highlight:: html+jinja5+6+If you have used a different template engine in the past and want to swtich7+to Jinja2 here is a small guide that shows the basic syntatic and semantic8+changes between some common, similar text template engines for Python.9+10+Jinja111+------12+13+Jinja2 is mostly compatible with Jinja1 in terms of API usage and template14+syntax. The differences between Jinja1 and 2 are explained in the following15+list.16+17+API18+~~~19+20+Loaders21+ 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>`.27+28+Loading 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.33+34+Automatic 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.41+42+i18n43+ 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`.47+48+Internal 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.53+54+Sandbox55+ 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`.58+59+Context60+ 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.64+65+66+Templates67+~~~~~~~~~68+69+Jinja2 has mostly the same syntax as Jinja1. The only difference is that70+assigning variables doesn't use `set` as keyword now. The following71+example shows a Jinja1 variable assignment::72+73+ {% set foo = 42 %}74+75+In Jinja2 the `set` is ommited::76+77+ {% foo = 42 %}78+79+Additionally macros require parentheses around the argument list now.80+81+Jinja2 allows dynamic inheritance now and dynamic includes. The old helper82+function `rendertemplate` is gone now, `include` can be used instead.83+Additionally includes no longer import macros and variable assignments, for84+that the new `import` tag is used. This concept is explained in the85+:ref:`import` documentation.86+87+Currently there is no support for the `recursive` modifier of for loops!88+89+90+Django91+------92+93+If you have previously worked with Django templates, you should find94+Jinja2 very familiar. In fact, most of the syntax elements look and95+work the same.96+97+However, Jinja2 provides some more syntax elements covered in the98+documentation and some work a bit different.99+100+This section covers the template changes. As the API is fundamentally101+different we won't cover it here.102+103+Method Calls104+~~~~~~~~~~~~105+106+In Django method calls work implicitly. With Jinja2 you have to specify that107+you want to call an object. Thus this Django code::108+109+ {% for page in user.get_created_pages %}110+ ...111+ {% endfor %}112+ 113+will look like this in Jinja::114+115+ {% for page in user.get_created_pages() %}116+ ...117+ {% endfor %}118+119+This allows you to pass variables to the function which is also used for macros120+which is not possible in Django.121+122+Conditions123+~~~~~~~~~~124+125+In Django you can use the following constructs to check for equality::126+127+ {% ifequals foo "bar" %}128+ ...129+ {% else %}130+ ...131+ {% endifequals %}132+133+In Jinja2 you can use the normal if statement in combination with operators::134+135+ {% if foo == 'bar' %}136+ ...137+ {% else %}138+ ...139+ {% endif %}140+141+You can also have multiple elif branches in your template::142+143+ {% if something %}144+ ...145+ {% elif otherthing %}146+ ...147+ {% elif foothing %}148+ ...149+ {% else %}150+ ...151+ {% endif %}152+153+Filter Arguments154+~~~~~~~~~~~~~~~~155+156+Jinja2 provides more than one argument for filters. Also the syntax for157+argument passing is different. A template that looks like this in Django::158+159+ {{ items|join:", " }}160+161+looks like this in Jinja2::162+163+ {{ items|join(', ') }}164+165+In fact it's a bit more verbose but it allows different types of arguments -166+including variables - and more than one of them.167+168+Tests169+~~~~~170+171+In addition to filters there also are tests you can perform using the is172+operator. Here are some examples::173+174+ {% if user.user_id is odd %}175+ {{ user.username|e }} is odd176+ {% else %}177+ hmm. {{ user.username|e }} looks pretty normal178+ {% endif %}179+180+181+Mako182+----183+184+.. highlight:: html+mako185+186+If you have used Mako so far and want to switch to Jinja2 you can configure187+Jinja2 to look more like Mako:188+189+.. sourcecode:: python190+191+ env = Environment('<%', '%>', '${', '}', '%')192+193+Once the environment is configure like that Jinja2 should be able to interpret194+a small subset of Mako templates. Jinja2 does not support embedded Python code195+so you would have to move that out of the template. The syntax for defs (in196+Jinja2 defs are called macros) and template inheritance is different too. The197+following Mako template::198+199+ <%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>206+207+Looks like this in Jinja2 with the above configuration::208+209+ <% 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 lines292 except TemplateSyntaxError, e:293 exc_type, exc_value, tb = translate_syntax_error(e)294 raise exc_type, exc_value, tb295 296- 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)303 304 def compile(self, source, name=None, filename=None, globals=None,305 raw=False):306 """Compile a node or template source code. The `name` parameter is375 unmodified linesmodified:jinja2/exceptions.py+6 added
16 unmodified lines17 class UndefinedError(TemplateError):18 """Raised if a template tries to operate on :class:`Undefined`."""19 20 21+class SecurityError(TemplateError):22+ """Raised if a template tries to do something insecure if the23+ sandbox is enabled.24+ """25+26+27 class TemplateNotFound(IOError, LookupError, TemplateError):28 """Raised if a template does not exist."""29 30 def __init__(self, name):29 unmodified linesmodified:jinja2/runtime.py+5 added-3 removed
304 unmodified lines305 self._undefined_name306 )307 else:308 hint = self._undefined_hint309- raise UndefinedError(hint)309+ raise self._undefined_exception(hint)310 311 312 class Undefined(object):313 """The default undefined type. This undefined type can be printed and8 unmodified lines322 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')328 328- 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 = exc334 335 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \336 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \337 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \76 unmodified linesmodified:jinja2/sandbox.py+50 added-19 removed
14 unmodified lines15 from types import FunctionType, MethodType, TracebackType, CodeType, \16 FrameType, GeneratorType17 from jinja2.runtime import Undefined18 from jinja2.environment import Environment19+from jinja2.exceptions import SecurityError20 21 22 #: maximum number of items a range may produce23 MAX_RANGE = 10000017 unmodified lines41 return rng42 43 44 def unsafe(f):44- """Mark a function as unsafe."""45+ """46+ Mark a function or method as unsafe::47+48+ @unsafe49+ def delete(self):50+ pass51+ """52 f.unsafe_callable = True53 return f54 55 56+def 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.61+62+ >>> 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('__')82+83+84 class 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.89+90+ 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 = True95 96 def __init__(self, *args, **kwargs):97 Environment.__init__(self, *args, **kwargs)2 unmodified lines100 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))108 109 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 is21 unmodified lines133 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)139 140 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 lines34 >>> env = MODULE.SandboxedEnvironment()35 >>> env.from_string("{{ foo.foo() }}").render(foo=MODULE.PrivateStuff())36 Traceback (most recent call last):37 ...38-TypeError: <bound method PrivateStuff.foo of PrivateStuff> is not safely callable38+SecurityError: <bound method PrivateStuff.foo of PrivateStuff> is not safely callable39 >>> env.from_string("{{ foo.bar() }}").render(foo=MODULE.PrivateStuff())40 u'23'41 42 >>> env.from_string("{{ foo._foo() }}").render(foo=MODULE.PublicStuff())43 Traceback (most recent call last):44 ...45-UndefinedError: access to attribute '_foo' of 'PublicStuff' object is unsafe.45+SecurityError: access to attribute '_foo' of 'PublicStuff' object is unsafe.46 >>> env.from_string("{{ foo.bar() }}").render(foo=MODULE.PublicStuff())47 u'23'48 49 >>> env.from_string("{{ foo.__class__ }}").render(foo=42)2 unmodified lines52 u''53 >>> env.from_string("{{ foo.__class__.__subclasses__() }}").render(foo=42)54 Traceback (most recent call last):55 ...56-UndefinedError: access to attribute '__class__' of 'int' object is unsafe.56+SecurityError: access to attribute '__class__' of 'int' object is unsafe.57 '''58 59 60 test_restricted = '''10 unmodified lines