Flask.url_for()错误:尝试生成没有推送应用程序上下文的URL

rsb*_*rsb 24 flask

我有一个简单的应用程序,我试图重定向favicon每个:

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'))
Run Code Online (Sandbox Code Playgroud)

但这失败了:

RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.
Run Code Online (Sandbox Code Playgroud)

所以,猜测,我试试这个:

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'))
Run Code Online (Sandbox Code Playgroud)

但得到一个不同的错误:

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.
Run Code Online (Sandbox Code Playgroud)

到底是怎么回事?

lor*_*. j 14

根据文件:

默认情况下,设置SERVER_NAME也可以在没有请求上下文但具有应用程序上下文的情况下生成URL.

因为您正在使用app_context,您可以设置SERVER_NAME配置值.

顺便说一下,正如doc:添加一个favicon所说:

<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
Run Code Online (Sandbox Code Playgroud)

对于大多数浏览器来说,上面的行应该足够了,我们不需要做任何其他事情.


小智 5

迟到的答案,我刚刚遇到了同样的问题。我没有看到像这样处理重定向的大缺点:

@app.route('/favicon.ico')
def favicon():
    return redirect(url_for('static', filename='favicon.ico'))
Run Code Online (Sandbox Code Playgroud)

这可以防止在应用程序准备好之前调用 url_for。

与仅在 HTML 中使用链接相反,每个站点在根级别都有 favicon.ico 和 robots.txt 是一个很好的做法 - 即使它们是空的。它避免了像这样的问题和其他给日志增加噪音的不必要的错误。

  • [文档](https://flask.palletsprojects.com/en/1.1.x/patterns/favicon/) 建议使用 `send_from_directory` 而不是 `redirect` (2认同)