I'm learning flask and python and cannot wrap my head around the way a typical flask application needs to be structured.
I need to access the app config from inside blueprint. Something like this
#blueprint.py
from flask import Blueprint
sample_blueprint = Blueprint("sample", __name__)
# defining a route for this blueprint
@sample_blueprint.route("/")
def index():
# !this is the problematic line
# need to access some config from the app
x = app.config["SOMETHING"]
# how to access app inside blueprint?
If importing app in blueprint is the solution, will this not result in circulat imports? i.e importing blueprint in app, importing app in blueprints?
This process should be applied before the routes.from flask import Flask from src. services. EnvironmentService import EnvironmentService app = Flask(__name__) # Here is our service env = EnvironmentService(). initialize(app.
The application context keeps track of the application-level data during a request, CLI command, or other activity. Rather than passing the application around to each function, the current_app and g proxies are accessed instead.
A Flask blueprint helps you to create reusable instances of your application. It does so by organizing your project in modules. Those modules are then registered the main application. They help in creating an application factory.
From the docs about appcontext:
The application context is what powers the current_app context local
Applied to your example:
from flask import Blueprint, current_app
sample = Blueprint('sample', __name__)
@sample.route('/')
def index():
x = current_app.config['SOMETHING']
For reference here is a small gist I put together, as mentioned in the comments.
In your app - when registering the blueprint - you need to push the context manually.
Refer to the snippet below and notice how the call-out to the init_db function is wrapped with the application context - the with ensures that the context is destroyed upon completion of your task.
def create_app():
app = Flask(__name__)
with app.app_context():
init_db()
return app
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With