Skip to content
Advertisement

How to add a function to app context in flask

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)

from flask import Flask
def create_app():
    app = Flask(__name__)
    with app.app_context():
        app.config['my_data'] = '<h1><b>My Data</b></h1>'

    @app.route('/')
    def home():
        return 'HomePage'

    return app

my_data can be retrieved from a blueprint using current_app

bp1.py

from flask import Blueprint, render_template, current_app
bp_1 = Blueprint()

@bp_1.route('/')
def home():
    return 'Homepage in bp_1'

@bp_1.route('/test1')
def test():
    return current_app.config['my_data']

Now I created a function rand_string in main.py and want to add it to the context.

main.py

from flask import Flask
import random

def rand_string(st): #st is just a string value
   a = random.randint(1, 10)
   return st*a

def create_app():
    app = Flask(__name__)

    with app.app_context():
        app.config['my_data'] = '<h1><b>My Data</b></h1>'

    @app.route('/')
    def home():
        return 'HomePage'

    return app

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.

from flask import Flask
import random

class RandString:
    @classmethod
    def rand_string(cls, st):  # st is just a string value
        a = random.randint(1, 10)
        return st * a

def create_app():
    app = Flask(__name__)

    with app.app_context():
        app.config['RAND_STRING'] = RandString

    @app.route('/')
    def home():
        return 'HomePage'

    return app

and call it:

@bp_1.route('/test1')
def test():
    rand_fuction = current_app.config['RAND_STRING']
    return {'rand_string': rand_fuction(2)}
5 People found this is helpful
Advertisement