Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading