SandboxedEnvironment Class

Inheritance diagram of SandboxedEnvironment

class SandboxedEnvironment(*args, **kwargs)

The sandboxed environment. It works like the regular environment but tells the compiler to generate sandboxed code. Additionally subclasses of this environment may override the methods that tell the runtime what attributes or functions are safe to access.

If the template tries to access insecure code a SecurityError is raised. However also other exceptions may occour during the rendering so the caller has to ensure that all exceptions are catched.

Methods

__init__(*args, **kwargs)
add_extension(extension) Adds an extension after the environment was created.
call(_SandboxedEnvironment__self, ...) Call an object from sandboxed code.
call_binop(context, operator, left, right) For intercepted binary operator calls (intercepted_binops()) this function is executed instead of the builtin operator.
call_unop(context, operator, arg) For intercepted unary operator calls (intercepted_unops()) this function is executed instead of the builtin operator.
compile(source[, name, filename, raw, ...]) Compile a node or template source code.
compile_expression(source[, undefined_to_none]) A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression.
compile_templates(target[, extensions, ...]) Finds all the templates the loader can find, compiles them and stores them in target.
extend(**attributes) Add the items to the instance of the environment if they do not exist yet.
from_string(source[, globals, template_class]) Load a template from a string.
get_or_select_template(template_name_or_list) Does a typecheck and dispatches to select_template() if an iterable of template names is given, otherwise to get_template().
get_template(name[, parent, globals]) Load a template from the loader.
getattr(obj, attribute) Subscribe an object from sandboxed code and prefer the attribute.
getitem(obj, argument) Subscribe an object from sandboxed code.
handle_exception([exc_info, rendered, ...]) Exception handling helper.
intercept_unop(operator) Called during template compilation with the name of a unary operator to check if it should be intercepted at runtime.
is_safe_attribute(obj, attr, value) The sandboxed environment will call this method to check if the attribute of an object is safe to access.
is_safe_callable(obj) Check if an object is safely callable.
iter_extensions() Iterates over the extensions by priority.
join_path(template, parent) Join a template with the parent.
lex(source[, name, filename]) Lex the given sourcecode and return a generator that yields tokens as tuples in the form (lineno, token_type, value).
list_templates([extensions, filter_func]) Returns a list of templates for this environment.
make_globals(d) Return a dict for the globals.
overlay([block_start_string, ...]) Create a new overlay environment that shares all the data with the current environment except of cache and the overridden attributes.
parse(source[, name, filename]) Parse the sourcecode and return the abstract syntax tree.
preprocess(source[, name, filename]) Preprocesses the source with all extensions.
select_template(names[, parent, globals]) Works like get_template() but tries a number of templates before it fails.
unsafe_undefined(obj, attribute) Return an undefined object for unsafe attributes.

Attributes

default_binop_table dict() -> new empty dictionary
default_unop_table dict() -> new empty dictionary
exception_formatter
exception_handler
intercepted_binops frozenset() -> empty frozenset object
intercepted_unops frozenset() -> empty frozenset object
lexer The lexer for this environment.
linked_to
overlayed bool(x) -> bool
sandboxed bool(x) -> bool
shared bool(x) -> bool

Descriptions

class SandboxedEnvironment

Method details

__init__(*args, **kwargs)
call(_SandboxedEnvironment__self, _SandboxedEnvironment__context, _SandboxedEnvironment__obj, *args, **kwargs)

Call an object from sandboxed code.

call_binop(context, operator, left, right)

For intercepted binary operator calls (intercepted_binops()) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators.

New in version 2.6.

call_unop(context, operator, arg)

For intercepted unary operator calls (intercepted_unops()) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators.

New in version 2.6.

getattr(obj, attribute)

Subscribe an object from sandboxed code and prefer the attribute. The attribute passed must be a bytestring.

getitem(obj, argument)

Subscribe an object from sandboxed code.

intercept_unop(operator)

Called during template compilation with the name of a unary operator to check if it should be intercepted at runtime. If this method returns True, call_unop() is excuted for this unary operator. The default implementation of call_unop() will use the unop_table dictionary to perform the operator with the same logic as the builtin one.

The following unary operators are interceptable: + and -

Intercepted calls are always slower than the native operator call, so make sure only to intercept the ones you are interested in.

New in version 2.6.

is_safe_attribute(obj, attr, value)

The sandboxed environment will call this method to check if the attribute of an object is safe to access. Per default all attributes starting with an underscore are considered private as well as the special attributes of internal python objects as returned by the is_internal_attribute() function.

is_safe_callable(obj)

Check if an object is safely callable. Per default a function is considered safe unless the unsafe_callable attribute exists and is True. Override this method to alter the behavior, but this won’t affect the unsafe decorator from this module.

unsafe_undefined(obj, attribute)

Return an undefined object for unsafe attributes.

Attribute details

default_binop_table = {'//': <built-in function floordiv>, '%': <built-in function mod>, '+': <built-in function add>, '*': <built-in function mul>, '-': <built-in function sub>, '/': <built-in function truediv>, '**': <built-in function pow>}

default callback table for the binary operators. A copy of this is available on each instance of a sandboxed environment as binop_table

default_unop_table = {'+': <built-in function pos>, '-': <built-in function neg>}

default callback table for the unary operators. A copy of this is available on each instance of a sandboxed environment as unop_table

intercepted_binops = frozenset([])

a set of binary operators that should be intercepted. Each operator that is added to this set (empty by default) is delegated to the call_binop() method that will perform the operator. The default operator callback is specified by binop_table.

The following binary operators are interceptable: //, %, +, *, -, /, and **

The default operation form the operator table corresponds to the builtin function. Intercepted calls are always slower than the native operator call, so make sure only to intercept the ones you are interested in.

New in version 2.6.

intercepted_unops = frozenset([])

a set of unary operators that should be intercepted. Each operator that is added to this set (empty by default) is delegated to the call_unop() method that will perform the operator. The default operator callback is specified by unop_table.

The following unary operators are interceptable: +, -

The default operation form the operator table corresponds to the builtin function. Intercepted calls are always slower than the native operator call, so make sure only to intercept the ones you are interested in.

New in version 2.6.

sandboxed = True

Inherited member details

add_extension(extension)

Adds an extension after the environment was created.

New in version 2.5.

compile(source, name=None, filename=None, raw=False, defer_init=False)

Compile a node or template source code. The name parameter is the load name of the template after it was joined using join_path() if necessary, not the filename on the file system. the filename parameter is the estimated filename of the template on the file system. If the template came from a database or memory this can be omitted.

The return value of this method is a python code object. If the raw parameter is True the return value will be a string with python code equivalent to the bytecode returned otherwise. This method is mainly used internally.

defer_init is use internally to aid the module code generator. This causes the generated code to be able to import without the global environment variable to be set.

New in version 2.4: defer_init parameter added.

compile_expression(source, undefined_to_none=True)

A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression.

This is useful if applications want to use the same rules as Jinja in template “configuration files” or similar situations.

Example usage:

>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True

Per default the return value is converted to None if the expression returns an undefined value. This can be changed by setting undefined_to_none to False.

>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined

New in version 2.1.

compile_templates(target, extensions=None, filter_func=None, zip='deflated', log_function=None, ignore_errors=True, py_compile=False)

Finds all the templates the loader can find, compiles them and stores them in target. If zip is None, instead of in a zipfile, the templates will be will be stored in a directory. By default a deflate zip algorithm is used, to switch to the stored algorithm, zip can be set to 'stored'.

extensions and filter_func are passed to list_templates(). Each template returned will be compiled to the target folder or zipfile.

By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set ignore_errors to False and you will get an exception on syntax errors.

If py_compile is set to True .pyc files will be written to the target instead of standard .py files.

New in version 2.4.

extend(**attributes)

Add the items to the instance of the environment if they do not exist yet. This is used by extensions to register callbacks and configuration values without breaking inheritance.

from_string(source, globals=None, template_class=None)

Load a template from a string. This parses the source given and returns a Template object.

get_or_select_template(template_name_or_list, parent=None, globals=None)

Does a typecheck and dispatches to select_template() if an iterable of template names is given, otherwise to get_template().

New in version 2.3.

get_template(name, parent=None, globals=None)

Load a template from the loader. If a loader is configured this method ask the loader for the template and returns a Template. If the parent parameter is not None, join_path() is called to get the real template name before loading.

The globals parameter can be used to provide template wide globals. These variables are available in the context at render time.

If the template does not exist a TemplateNotFound exception is raised.

Changed in version 2.4: If name is a Template object it is returned from the function unchanged.

handle_exception(exc_info=None, rendered=False, source_hint=None)

Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template.

iter_extensions()

Iterates over the extensions by priority.

join_path(template, parent)

Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the template parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name.

Subclasses may override this method and implement template path joining here.

lex(source, name=None, filename=None)

Lex the given sourcecode and return a generator that yields tokens as tuples in the form (lineno, token_type, value). This can be useful for extension development and debugging templates.

This does not perform preprocessing. If you want the preprocessing of the extensions to be applied you have to filter source through the preprocess() method.

list_templates(extensions=None, filter_func=None)

Returns a list of templates for this environment. This requires that the loader supports the loader’s list_templates() method.

If there are other files in the template folder besides the actual templates, the returned list can be filtered. There are two ways: either extensions is set to a list of file extensions for templates, or a filter_func can be provided which is a callable that is passed a template name and should return True if it should end up in the result list.

If the loader does not support that, a TypeError is raised.

New in version 2.4.

make_globals(d)

Return a dict for the globals.

overlay(block_start_string=missing, block_end_string=missing, variable_start_string=missing, variable_end_string=missing, comment_start_string=missing, comment_end_string=missing, line_statement_prefix=missing, line_comment_prefix=missing, trim_blocks=missing, extensions=missing, optimized=missing, undefined=missing, finalize=missing, autoescape=missing, loader=missing, cache_size=missing, auto_reload=missing, bytecode_cache=missing)

Create a new overlay environment that shares all the data with the current environment except of cache and the overridden attributes. Extensions cannot be removed for an overlayed environment. An overlayed environment automatically gets all the extensions of the environment it is linked to plus optional extra extensions.

Creating overlays should happen after the initial environment was set up completely. Not all attributes are truly linked, some are just copied over so modifications on the original environment may not shine through.

parse(source, name=None, filename=None)

Parse the sourcecode and return the abstract syntax tree. This tree of nodes is used by the compiler to convert the template into executable source- or bytecode. This is useful for debugging or to extract information from templates.

If you are developing Jinja2 extensions this gives you a good overview of the node tree generated.

preprocess(source, name=None, filename=None)

Preprocesses the source with all extensions. This is automatically called for all parsing and compiling methods but not for lex() because there you usually only want the actual source tokenized.

select_template(names, parent=None, globals=None)

Works like get_template() but tries a number of templates before it fails. If it cannot find any of the templates, it will raise a TemplatesNotFound exception.

New in version 2.3.

Changed in version 2.4: If names contains a Template object it is returned from the function unchanged.

exception_formatter = None
exception_handler = None
lexer

The lexer for this environment.

linked_to = None
overlayed = False
shared = False

Table Of Contents

Previous topic

ImmutableSandboxedEnvironment Class

Next topic

SecurityError