gpt4 book ai didi

python - 有没有办法限制在 Django 模板中使用标签和过滤器?

转载 作者:行者123 更新时间:2023-11-28 21:56:12 24 4
gpt4 key购买 nike

我知道 Django 已经为设计师提供了一个很好的模板系统,但我想知道是否可以限制某些模板标签和过滤器的使用。

我们正在为设计人员构建一个 Django 插件,使模板开发更加开放,但我们希望隐藏 Django 模板系统的一些逻辑,只向设计人员公开必要的部分。

例如:如何防止使用 {% load %} 模板标签并只预加载我想要的标签?

最佳答案

试试这个装饰器:Safe template decorator

来自作者描述:

A decorator that restricts the tags and filters available to template loading and parsing within a function.

This is mainly meant to be used when granting users the power of the DTL. You obviously don't want users to be able to do things that could be potentially malicious.

The {% ssi %} tag, for example, could be used to display sensitive data if improperly configured.

{% load %} gives them access to all the unlimited python code you wrote in your templatetags. {% load sudo %}{% sudo rm -rf / %} o_0

Note that the "load" tag (among others) is not listed in the default tag whitelist. If you parse a template (however indirectly) in a function decorated with this, unlisted builtin tags will behave like undefined tags (ie, they will result in a TemplateSyntaxError).

Since {% load %} is not whitelisted, you may want to include some custom tags or filters as "builtins" for convenience. Simply put the module paths to the libraries to include in the extra kwarg or the extra_libraries list. Generally, this is not recommended, as these libraries need to be carefully and defensively programmed.

NOTE: This does not do anything about cleaning your rendering context! That's completely up to you! This merely restricts what tags and filters are allowed in the templates.

例子:

from django.template.loader import get_template
safe_get_template = use_safe_templates(get_template)
tmpl = safe_get_template('myapp/some_template.html')

from django.template import Template
use_safe_templates(Template)('{% load sudo %}')
# TemplateSyntaxError: Invalid block tag 'load'

关于python - 有没有办法限制在 Django 模板中使用标签和过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21884402/

24 4 0