Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flask

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?

like image 898
rsb Avatar asked Aug 01 '15 20:08

rsb


1 Answers

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.

like image 156
lord63. j Avatar answered Sep 16 '22 21:09

lord63. j