Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: How to use app context inside blueprints?

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?

like image 342
palerdot Avatar asked Sep 29 '16 11:09

palerdot


People also ask

How do I use app config in Blueprint Flask?

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.

What is the application context in Flask?

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.

What is the point of Flask blueprint?

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.


2 Answers

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.

like image 103
rtzll Avatar answered Sep 16 '22 12:09

rtzll


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

like image 44
nauf Avatar answered Sep 16 '22 12:09

nauf