看完文档,mark_safe()的功能目前还不清楚。我猜这与 CSRF 的东西有关。但是为什么以及何时应该使用 mark_safe() 呢?
这是文档
mark_safe(s)
Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string or unicode object is appropriate.
Can be called multiple times on a single string.
For building up fragments of HTML, you should normally be using django.utils.html.format_html() instead.
String marked safe will become unsafe again if modified. For example:
最佳答案
Django 是一个框架,它默认尝试做“正确”的事情。这意味着当您做最简单的事情时,您可能正在做正确的事情。
现在让我们看一下 php 和 python 中的一些模板:
PHP:
<? echo $foo ?>
可以给出:
<script src="evil">
Django :
{{ foo }}
使用相同的输入给出:
>script src="evil"<
现在假设您想要放置一个链接 <a href="link">text</a>
。然后 django 将使用 <>
将其渲染为文本再次。如果您知道自己在做什么,现在可以使用 mark_safe
表明文本是可信的(即不是来自用户输入)。
通常您会使用{{ foo|safe }}
或{% autoescape off %}{{ foo }}{% endautoescape %}
作为 django 程序员在模板中,当字符串被声明为安全时会更清楚。
那么,mark_safe
在哪里?用过的?当您编写自己的模板标签或过滤器时,您需要将字符串标记为对 python 安全,因为开发人员会假设 {{ foo|mylinkifyfunction }}
做了正确的事情,即,它转义了 url foo,但没有转义 HTML 代码 <a href=""></a>
围绕网址。
示例实现可以是:
def mylinkifyfunction(url):
escaped_url = escape_url(url) # Take care of escaping the URL in a safe way
generated_html = f'<a href="{escaped_url}">{escaped_url}</a>' # This string could be dangerous, if it would use url instead of escaped_url
return mark_safe(generated_html) # mark the string as safe, because it should be rendered as unescaped HTML
该示例假设 escape_url
返回不包含 HTML 或 "
的字符串.
关于python - 为什么以及何时使用 Django mark_safe() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32799615/