Flask.url_for() 错误:尝试在没有推送应用程序上下文的情况下生成 URL [英] Flask.url_for() error: Attempted to generate a URL without the application context being pushed
问题描述
我有一个微不足道的应用程序,我试图在其中重定向网站图标:
I have a trivial app where I'm trying to redirect the favicon per:
http://flask.pocoo.org/docs/0.10/patterns/favicon/
app = flask.Flask(__name__)
app.add_url_rule('/favicon.ico', redirect_to=flask.url_for('static', filename='favicon.ico'))
但这失败了:
RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.
所以,猜测,我试试这个:
So, guessing, I try this:
app = flask.Flask(__name__)
with app.app_context():
flask.current_app.add_url_rule('/favicon.ico', redirect_to=flask.url_for('static', filename='favicon.ico'))
但得到一个不同的错误:
But get a different error:
RuntimeError: Application was not able to create a URL adapter for request independent URL generation. You might be able to fix this by setting the SERVER_NAME config variable.
这是怎么回事?
推荐答案
根据 文档:
默认情况下,设置 SERVER_NAME 也会启用 URL 生成,无需请求上下文但具有应用程序上下文.
Setting a SERVER_NAME also by default enables URL generation without a request context but with an application context.
由于您使用的是 app_context
,您可以设置 SERVER_NAME
配置值.
since you're using app_context
, you may set the SERVER_NAME
Configuration Value.
顺便说一下,作为 doc:Adding a favicon 说:
By the way, as the doc:Adding a favicon says:
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
对于大多数浏览器来说,上面这行应该足够了,我们不需要做任何其他事情.
the above line should be enough for most browsers, we don't have to do any other things.
这篇关于Flask.url_for() 错误:尝试在没有推送应用程序上下文的情况下生成 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!