为什么以及何时使用Django mark_safe()函数 [英] Why and When to use Django mark_safe() function
问题描述
阅读文档后, mark_safe()尚不清楚。我想这与CSRF有关。但是,为什么以及何时使用mark_safe()?
After reading the document, the function of mark_safe() is still unclear. I guess it is related to CSRF stuff. But why and when shall the mark_safe() be used?
此处是文档
mark_safe(s)
mark_safe(s)
为了(HTML)
输出目的,将字符串明确标记为安全。返回的对象可以在任何适合字符串
或unicode对象的地方使用。
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.
要构建HTML片段,通常应改用
django.utils.html.format_html()。
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是一个框架,试图做正确的事情默认情况下。
Django is a framework, which tries to do "the right" thing by default. This means when you do the most simple thing, you're propably doing the right thing.
现在,让我们看一下php和python中的一些模板:
Now let's look at some template in php and python:
PHP:
<? echo $foo ?>
可以给:
<script src="evil">
Django:
{{ foo }}
给出相同的输入:
>script src="evil"<
现在假设您要放置链接< a href = link> text< / a>
。然后django将再次使用& lt;&
将其呈现为文本。如果您知道自己在做什么,则现在可以使用 mark_safe
表示文本受信任(即不是来自userinput)。
Now assume, you want to place a link <a href="link">text</a>
. Then django will render it as text using <>
again. If you know what you're doing, you can now use mark_safe
to indicate that the text is trusted (i.e. not coming from userinput).
通常,您将使用 {{foo | safe}}
或 {%自动转义%} {{foo}} { %endautoescape%}
在您的模板中以django程序员的身份出现,这在字符串被声明为安全字符串时更加清楚。
Usually you will use {{ foo|safe }}
or {% autoescape off %}{{ foo }}{% endautoescape %}
in your templates as django programmer, which is more clear when the string is declared as being safe.
因此,在哪里使用了 mark_safe
?当您编写自己的templatetags或过滤器时,您需要将字符串从python标记为安全,因为开发人员会假设{{foo | mylinkifyfunction}}做正确的事情(即,它对url foo进行了转义,但没有转义)网址中的< a href =>< / a>
)。
So, where is mark_safe
used? When you write own templatetags or filters, then you need to mark the string as safe from python, because the developer will assume, that {{ foo|mylinkifyfunction }} does the right thing (i.e. it escapes the url foo, but does not escape the <a href=""></a>
around the url).
这篇关于为什么以及何时使用Django mark_safe()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!