Flask.url_for() error: Attempted to generate a URL without the application context being pushed

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

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?

回答1:

According to the doc:

Setting a SERVER_NAME also by default enables URL generation without a request context but with an application context.

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!