2

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.

xaander1
  • 1,064
  • 2
  • 12
  • 40

1 Answers1

2

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.

simkusr
  • 770
  • 2
  • 11
  • 20
  • i hadn't looked it that way..that's smart...would it possibly work with functions...or import statements? – xaander1 Mar 24 '20 at 09:00
  • 1
    Honestly, I haven't tried that, because, with e.g. functions, I do import them from the app, like `from app import my_function` and similar with statements. The `current_app.config` is meant for passing variables as described in the official [documentation](https://flask.palletsprojects.com/en/1.1.x/config/) – simkusr Mar 24 '20 at 09:10
  • Yeah i just read the documentation...its for passing configuration meaning custom variables wouldn't work. Also functions obviously – xaander1 Mar 24 '20 at 09:14
  • Yes, for the configuration meaning variables, but you can use that also. Or you could even use `flask.session` as it would be available globally also. But passing functions... I would offer simply to import where and when you need it. – simkusr Mar 24 '20 at 10:38
  • I''ll check out flask session but i think i found a better way calling the blueprint programatically and encapsulating into a class. I marked my question duplicate after i saw the answer. https://stackoverflow.com/questions/28640081/how-to-pass-arbitrary-arguments-to-a-flask-blueprint However your method is very handy...i could pass one password and username to all my blueprint api's – xaander1 Mar 24 '20 at 12:06