本文介绍了Flask.url_for()错误:尝试生成一个没有推送应用程序上下文的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的应用程序,我试图重定向的favicon每个:
app = flask.Flask(__ name__)
app.add_url_rule('/ favicon.ico',redirect_to = flask.url_for('static',filename ='favicon.ico' ))
但是这个失败:
RuntimeError:试图在没有推送应用程序上下文的情况下生成一个URL。这应该在应用程序上下文可用时执行。
所以,猜一猜,我试试这个:
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'))
但是得到一个不同的错误:
RuntimeError:应用程序无法为请求独立的URL生成创建URL适配器。您可以通过设置SERVER_NAME配置变量来解决这个问题。
这是怎么回事?
解决方案
根据说:
< link rel =快捷方式iconhref ={{url_for('static',filename ='favicon.ico')}}>
上面的行对于大多数浏览器来说应该是足够的,我们不需要做任何其他的事情。
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'))
But this fails with:
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.
What is going on?
解决方案
According to the doc:
since you're using app_context
, you may set the SERVER_NAME
Configuration Value.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!