Search code examples
pythonflaskblueprint

Use flask variable outside of context


In the Flask application (initialized in __init__.py) I have two blueprints - auth and main . In the auth blueprint I'm trying to set some variable (will be loaded from db and depends from current_user.get_id()) which should be used in main blueprint as url-prefix:

auth.py

@auth.route('/login', methods=['POST'])
def login_post():
    username = request.form.get('username')
    password = request.form.get('password')

    user_inst = user.query.filter_by(username=username).first()


    if not user_inst or not check_password_hash(user_inst.password, password):
        flash('Invalid credentials. Check you input and try again.')
        return redirect(url_for('auth.login')) 

    login_user(user_inst)
    
    g.team_name = 'some_team_name'
    #session['team_name'] = 'some_team_name'
    
    # if the above check passes, then we know the user has the right credentials
    return redirect(url_for('main.some_func'))

In the main blueprint, it's required to get the team_name variable:

main = Blueprint('main', __name__, static_folder="static", static_url_path="", url_prefix=g.team_name)

Could you please advise is there a proper way to import variable from auth to main (before its initializing) without getting:

RuntimeError: Working outside of application context.

Solution

  • Basic fix of your problem is registering blueprints within app.app_context():

    And seems like it is your first flask project and it is a common problem with thinking about the project structure. Read about Flask application factory pattern and apply it.

    your_app/__init__.py

    def create_app(app_config):
        app = Flask(__name__)
        with app.app_context():
            from your_app.somewhere import team_name
    
            app.register_blueprint(team_name)
        return app