当前位置: 首页 > 文档资料 > Jinja2 中文文档 >

沙箱

优质
小牛编辑
136浏览
2023-12-01

Jinja2 沙箱用于为不信任的代码求值。访问不安全的属性和方法是被禁止的。

假定在默认配置中 env 是一个 SandboxedEnvironment 实例,下面的代码展示 了它如何工作:

>>> env.from_string("{{ func.func_code }}").render(func=lambda:None)
u&"" title="jinja2.sandbox.SecurityError">SecurityError is
raised.  However also other exceptions may occour during the rendering so
the caller has to ensure that all exceptions are catched.

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.

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.

2.6 新版功能.

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.

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.

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&"" title="jinja2.sandbox.modifies_known_mutable">modifies_known_mutable() function.

exception jinja2.sandbox.SecurityError(message=None)

Raised if a template tries to do something insecure if the sandbox is enabled.

jinja2.sandbox.unsafe(f)

Marks a function or method as unsafe.

@unsafe
def delete(self):
    pass
jinja2.sandbox.is_internal_attribute(obj, attr)

Test if the attribute given is an internal python attribute. For example this function returns True for the func_code attribute of python objects. This is useful if the environment method is_safe_attribute() is overridden.

>>> from jinja2.sandbox import is_internal_attribute
>>> is_internal_attribute(lambda: None, "func_code")
True
>>> is_internal_attribute((lambda x:x).func_code, &"" title="jinja2.sandbox.SandboxedEnvironment.intercepted_binops">SandboxedEnvironment.intercepted_binops 属性。当需要拦截的运算符
被添加到这个集合, Jinja2 会生成调用
SandboxedEnvironment.call_binop() 函数的字节码。对于一元运算符,
必须替代地使用 unary 属性和方法。

SandboxedEnvironment.call_binop 的默认实现会使用 SandboxedEnvironment.binop_table 来把运算符标号翻译成执行默认 运算符行为的回调。

这个例子展示了幂( ** )操作符可以在 Jinja2 中禁用:

from jinja2.sandbox import SandboxedEnvironment


class MyEnvironment(SandboxedEnvironment):
    intercepted_binops = frozenset(['**'])

    def call_binop(self, context, operator, left, right):
        if operator == '**':
            return self.undefined('the power operator is unavailable')
        return SandboxedEnvironment.call_binop(self, context,
                                               operator, left, right)

确保始终调入 super 方法,即使你不拦截这个调用。 Jinja2 内部会调用 这个方法来对表达式求值。