编程语言
首页 > 编程语言> > python – 为什么要使用`url_for`?

python – 为什么要使用`url_for`?

作者:互联网

我使用Flask编写Web应用程序,并且我想知道使用url_for在模板和应用程序代码中生成链接的原因.

这样做可以获得什么:

<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">

还有这个:

<ul>
    <li><a href="{{ url_for('index') }}">Home</a></li> 
    <li><a href="{{ url_for('about') }}">About Us</a></li>
    <li><a href="{{ url_for('contact') }}">Contact</a></li>
</ul>

而不是硬编码路径?

解决方法:

flask documentation,

flask.url_for(endpoint, **values)

Generates a URL to the given endpoint with the method provided.

Variable arguments that are unknown to the target endpoint are
appended to the generated URL as query arguments. If the value of a
query argument is None, the whole pair is skipped. In case blueprints
are active you can shortcut references to the same blueprint by
prefixing the local endpoint with a dot (.).

This will reference the index function local to the current blueprint:

url_for(‘.index’)

现在,您可以使用与端点进行反向匹配的url_for,而不是指定静态URL到达端点.

当您具有可能要在运行时指定的参数时,它尤其有用.

{{ url_for('static', filename='css/main.css') }}

您可以在运行时动态计算filename =’…’).

进一步扩展,

external=True 

选项启用重定向

标签:application-design,python,flask
来源: https://codeday.me/bug/20190825/1720978.html