I am trying to use flask blueprints to organize the flask projects I build. And I found out a that context can be used to export variables from main.py to blueprints.
main.py(or _init_.py)
JavaScript
x
12
12
1
from flask import Flask
2
def create_app():
3
app = Flask(__name__)
4
with app.app_context():
5
app.config['my_data'] = '<h1><b>My Data</b></h1>'
6
7
@app.route('/')
8
def home():
9
return 'HomePage'
10
11
return app
12
my_data can be retrieved from a blueprint using current_app
bp1.py
JavaScript
1
11
11
1
from flask import Blueprint, render_template, current_app
2
bp_1 = Blueprint()
3
4
@bp_1.route('/')
5
def home():
6
return 'Homepage in bp_1'
7
8
@bp_1.route('/test1')
9
def test():
10
return current_app.config['my_data']
11
Now I created a function rand_string in main.py and want to add it to the context.
main.py
JavaScript
1
19
19
1
from flask import Flask
2
import random
3
4
def rand_string(st): #st is just a string value
5
a = random.randint(1, 10)
6
return st*a
7
8
def create_app():
9
app = Flask(__name__)
10
11
with app.app_context():
12
app.config['my_data'] = '<h1><b>My Data</b></h1>'
13
14
@app.route('/')
15
def home():
16
return 'HomePage'
17
18
return app
19
How can I do it and how can I retrieve the rand_string function from the bp_1 using current_app?
Advertisement
Answer
You can add rand_string to a class and register this class to config. After that you can call it.
JavaScript
1
21
21
1
from flask import Flask
2
import random
3
4
class RandString:
5
@classmethod
6
def rand_string(cls, st): # st is just a string value
7
a = random.randint(1, 10)
8
return st * a
9
10
def create_app():
11
app = Flask(__name__)
12
13
with app.app_context():
14
app.config['RAND_STRING'] = RandString
15
16
@app.route('/')
17
def home():
18
return 'HomePage'
19
20
return app
21
and call it:
JavaScript
1
5
1
@bp_1.route('/test1')
2
def test():
3
rand_fuction = current_app.config['RAND_STRING']
4
return {'rand_string': rand_fuction(2)}
5