38

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?

rsb
  • 1,020
  • 1
  • 10
  • 25

3 Answers3

26

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.

Neil Katin
  • 27
  • 4
lord63. j
  • 4,500
  • 2
  • 22
  • 30
  • What if I would like to have a favicon without html template rendering? Let's say, on the classic "hello world" example. – alec_djinn Nov 22 '18 at 14:44
  • 1
    The docs also suggest adding the `app.add_url_rule` as per the question for account for older browsers – Tom Malkin Oct 17 '19 at 22:07
9

Late answer, I've just run into the same problem. I don't see a big downside in handling the redirect like this instead:

@app.route('/favicon.ico')
def favicon():
    return redirect(url_for('static', filename='favicon.ico'))

This prevents url_for from being called before the application is ready.

To give a counterpoint to using a link in the HTML only, it's a good practice for every site to have a favicon.ico and robots.txt at the root level - even if they're empty. It avoids problems like this and other unnecessary errors that adds noise to logs.

Michael Mulqueen
  • 1,033
  • 10
  • 11
  • 2
    The [docs](https://flask.palletsprojects.com/en/1.1.x/patterns/favicon/) suggest using `send_from_directory` rather than `redirect` – Tom Malkin Oct 17 '19 at 22:08
3

Don't put this in the app but in the html file

    <html lang="en">
    <head>
        <title>{{ title }}</title>
         <meta charset="utf-8">
         <meta name="viewport" content="width=device-width/2, initial-scale=1">
         <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    </head>
RobPL
  • 55
  • 3