Working outside of application context when using flask_api_key

33 views Asked by At

Based on https://pypi.org/project/flask-api-key/ I am trying to implement:

from flask import Flask
from flask_api_key import APIKeyManager, api_key_required

app = Flask(__name__)

my_key_manager = APIKeyManager(app)
my_key_manager.create("First_key")

@app.route("/")
def home():
    return "hi Home"

@app.route("/protected")
@api_key_required
def protected():
    return "hi protected"

if __name__ == "__main__":
    app.run(debug=True)

Error message:

"RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve this, set up an application context with app.app_context(). See the documentation for more information."

1

There are 1 answers

1
nsw42 On

A Flask app context can be created as a Python context manager:

with app.app_context():
    my_key_manager.create("my_first_key")

See https://flask.palletsprojects.com/en/2.3.x/appcontext/ if you want background information about what the app context is.

NB, when running an updated version of your code, I then hit another issue with the flask_api_key library, which looks like this issue: https://github.com/jthop/flask-api-key/issues/2