0

I followed the instructions for serving favicons from Flask's docs, and added the line app.add_url_rule('/favicon.ico', redirect_to=url_for('static', filename='favicon.ico')) to my server. But when I run it I get this error:

  File "server.py", line X, in __init__
    redirect_to=url_for('static', filename='favicon.ico'))
  File "/python3.9/site-packages/flask/helpers.py", line 306, in url_for
    raise RuntimeError(
RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.

I am using a class-based server, with the basics reproduced here:

from flask import Flask, Response, render_template, request, redirect, url_for
from werkzeug.exceptions import HTTPException

class Server:
    def __init__(self, host, port):
        self.app = Flask(__name__)
        self.host = host
        self.port = port

        # Set up routes:
        self.app.route("/")(self.index)

        # Error occurs here:
        self.app.add_url_rule('/favicon.ico',
                         redirect_to=url_for('static', filename='favicon.ico'))
        
        self.app.register_error_handler(HTTPException, self.handle_http_error)

    def index(self):
        return render_template("index.html")

    @staticmethod
    def error(msg):
        """Custom error handler"""
        return render_template("error.html", msg=msg)

    def handle_http_error(self, e):
        return self.error(f"{e.code} {e.name}: {e.description}"), e.code

    def start(self):
        self.app.run(host=self.host, port=self.port)


server = Server("localhost", 8080)
server.start()

My guess is I put the line to serve the favicon in the wrong spot. The error message says This has to be executed when application context is available., but I'm not sure exactly what that means. I saw this question but the answer is a bit vague, and I couldn't figure out how to incorporate it into my code. Also, that user had a with statement, which I tried but couldn't get to work. I tried adding a SERVER_NAME config variable but it didn't change anything (I also had no idea what to put in it, so that's probably another issue).

  • There's a similar question [here](https://stackoverflow.com/questions/31766082/flask-url-for-error-attempted-to-generate-a-url-without-the-application-conte) that may be of interest. – larsks Jun 03 '23 at 02:18
  • Does this answer your question? [Flask.url\_for() error: Attempted to generate a URL without the application context being pushed](https://stackoverflow.com/questions/31766082/flask-url-for-error-attempted-to-generate-a-url-without-the-application-conte) – Mike 'Pomax' Kamermans Jun 03 '23 at 02:19
  • Couldn't get those answers and a `with` statement to work, I'm probably not implementing them right. – TheTridentGuy supports Ukraine Jun 03 '23 at 02:31

0 Answers0