Flask pass a variable from apps main file to a blueprint

Viewed 1488

How can i pass a variable to a blueprint from the apps main file

Lets say i had the following sample app.

#app.py

from flask import Flask
from example_blueprint import example_blueprint

data_to_pass="Hurray, You passed me"
app = Flask(__name__)
app.register_blueprint(example_blueprint)

#Blueprint

from flask import Blueprint

example_blueprint = Blueprint('example_blueprint', __name__)

@example_blueprint.route('/')
def index():
    return "This is an example app"

How do i pass data_to_pass to the blueprint ?? Is there a flask inbuilt way? I am trying to avoid importing the whole app.py file...it doesnt seem elegant.

1 Answers

If it's a configuration variable, then you could in your app.py add like this app.config['data_to_pass'] and in your blueprint.py you could from flask import current_app and then you can use it like this current_app.config['data_to_pass']. So the code should look like this:


#app.py

from flask import Flask
from example_blueprint import example_blueprint

data_to_pass="Hurray, You passed me"
app = Flask(__name__)
app.config['data_to_pass'] = data_to_pass

app.register_blueprint(example_blueprint)

and then in the blueprint, you can read it like this

#Blueprint

from flask import Blueprint, current_app

example_blueprint = Blueprint('example_blueprint', __name__)

@example_blueprint.route('/')
def index():
    data_to_pass = current_app.config['data_to_pass']
    return "This is an example app"

This is the best way to use configuration variables I think.

Related