votes up 1

Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.

Package:
flask
github stars 56479
Exception Class:
RuntimeError

Raise code

""" am _anchor: if provided this is added as anchor to the URL.
    :param _method: if provided this explicitly specifies an HTTP method.
    """
    appctx = _app_ctx_stack.top
    reqctx = _request_ctx_stack.top

    if appctx is None:
        raise RuntimeError(
            "Attempted to generate a URL without the application context being"
            " pushed. This has to be executed when application context is"
            " available."
        )

    # If request specific information is available we have some extra
    # features that support "relative" URLs.
    if r

Ways to fix

votes up 0 votes down

Summary:

The url_for function must always be called within the application context. i.e within a view, with app.app_context, by manually pushing the app ctx stack.

Code to reproduce:

from flask import url_for, Flask

app = Flask(__name__)

@app.route("/")
def index():
    return ""


print(url_for("app.index"))
app.run()

Code to fix

from flask import url_for, Flask

app = Flask(__name__)

@app.route("/")
def index():
    print(url_for("app.index")) # call within a view
    return ""

with app.app_context():
    print(url_for("app.index")) # or Call with context
app.run()
May 27, 2021 cRyp70s answer
cRyp70s 113

Add a possible fix

Please authorize to post fix