url_for 使用 & 创建一个 url 查询字符串

jan*_*ins 4 python jinja2 query-string flask python-3.x

假设我在烧瓶应用程序的 html 模板中有以下脚本

<script type="text/javascript">
  console.log('{{ url_for('root', arg1='hello', arg2='world') }}')
<script>
Run Code Online (Sandbox Code Playgroud)

我有一个烧瓶端点 root()

@app.route('/', methods=['GET'])
def root():
  print(print(request.args))
Run Code Online (Sandbox Code Playgroud)

当我调用我的页面时,内部脚本被呈现为

console.log('/api/art_structure?arg2=world&amp;arg1=hello')
Run Code Online (Sandbox Code Playgroud)

当我调用这个 url 时,我的request.args字典是:

ImmutableMultiDict([('amp;arg1', 'hello'), ('arg2', 'world')])
Run Code Online (Sandbox Code Playgroud)

这是不正确的,因为 的键arg1是错误的。有什么线索可以防止 jinja2 转换&&amp;

zvo*_*one 8

与号

正确的网址是/api/art_structure?arg2=world&arg1=hello.

上述 URL 的问题是 & 符号 ( &) 不能直接写在 HTML 中,因为 & 符号用于实体引用。例如,要<在 HTML 中编写不是标记开头的字符,可以编写&lt;. 正因为如此,要写&,人们应该逃避它,即把它写成&amp;

Jinja2 模板引擎默认这样做。因此,您可以转储任何字符串变量的内容,即使它包含特殊字符,并且它们将被正确转义,例如&将变成&amp;您的情况。

这是如何运作的?

所以,如果你真的把它放在你的 jinja 模板中:<a href="{{ url_for('root', arg1='hello', arg2='world') }}">link</a>,它会写出以下 HTML 代码:<a href="/api/art_structure?arg2=world&amp;arg1=hello">link</a>,如果你在浏览器中点击链接,它会正确地替换&amp;&并打开/api/art_structure?arg2=world&arg1=hello

(但是请注意,将&原样写入 HTML 有时也可以正常工作,因为浏览器可能会猜测如何修复错误)

那么为什么在这种情况下它不能简单地工作呢?

因为你生成JavaScript,而不是HTML(你是内生成代码<script>,并</script>在JavaScript中,&是罚款,不应该被转义,所以你可以自由地写,因为它是要告诉神社,你不希望它了字符串,您可以使用safe过滤器,即{{ url_for('root', arg1='hello', arg2='world') | safe}}.