pythonflaskkeycloak

Python Flask can't access app inside Blueprint


I've been trying to build a keycloak oidc authentication flow with flask.

Before using oidc, I need to initialize the oidc variable inside my /auth blueprint. I can't get it running.

from flask import Blueprint, current_app
from flask_oidc import OpenIDConnect

auth = Blueprint('auth', __name__, static_folder="static", template_folder="templates")

app = current_app._get_current_object()

with app.app_context():
    oidc = OpenIDConnect(app)

I am getting the following error:

RuntimeError: Working outside of application context.

What can I do to use the OpenIDConnect inside the Blueprint? I know similar questions have already been asked multiple times but I can't get it running with their solutions.


Solution

  • If you're using Flask app factory pattern, i would recommend initializing Flask-OIDC using init_app method.

    Some example code:

    from flask import Flask
    from flask_oidc import OpenIDConnect
    
    oidc = OpenIDConnect()
    
    def create_app():
        app = Flask(__name__)
    
        # Initialize OIDC
        oidc.init_app(app)
    
        return app
    

    Now, you can import oidc from your application if you need to access the instance, for example from app import oidc.

    https://flask-oidc.readthedocs.io/en/latest/#flask_oidc.OpenIDConnect.init_app