The Jinja sandbox can be used to render untrusted templates. Access to attributes, method calls, operators, mutating data structures, and string formatting can be intercepted and prohibited.
from jinja2.sandbox import SandboxedEnvironment
env = SandboxedEnvironment()
func = lambda: "Hello, Sandbox!"
env.from_string("{{ func() }}").render(func=func)
'Hello, Sandbox!'
env.from_string("{{ func.__code__.co_code }}").render(func=func)
Traceback (most recent call last):
...
SecurityError: access to attribute '__code__' of 'function' object is unsafe.
A sandboxed environment can be useful, for example, to allow users of an internal reporting system to create custom emails. You would document what data is available in the templates, then the user would write a template using that information. Your code would generate the report data and pass it to the user’s sandboxed template to render.