Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask, Blueprint, current_app

I am trying to add a function in the Jinja environment from a blueprint (a function that I will use into a template).

Main.py

app = Flask(__name__)
app.register_blueprint(heysyni)

MyBluePrint.py

heysyni = Blueprint('heysyni', __name__)
@heysyni.route('/heysyni'):
    return render_template('heysyni.html', heysini=res_heysini)

Now in MyBluePrint.py, I would like to add something like :

def role_function():
    return 'admin'

app.jinja_env.globals.update(role_function=role_function)

I will then be able to use this function in my template. I cannot figure out how I can access the application since

app = current_app._get_current_object()

returns the error:

working outside of request context

How can I implement such a pattern ?

like image 756
gpasse Avatar asked Mar 30 '12 15:03

gpasse


1 Answers

The message error was actually pretty clear :

working outside of request context

In my blueprint, I was trying to get my application outside the 'request' function :

heysyni = Blueprint('heysyni', __name__)

app = current_app._get_current_object()
print(app)

@heysyni.route('/heysyni/')
def aheysyni():
    return 'hello'

I simply had to move the current_app statement into the function. Finally it works that way :

Main.py

from flask import Flask
from Ablueprint import heysyni

app = Flask(__name__)
app.register_blueprint(heysyni)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run(debug=True)

Ablueprint.py

from flask import Blueprint, current_app

heysyni = Blueprint('heysyni', __name__)

@heysyni.route('/heysyni/')
def aheysyni():
    # Got my app here
    app = current_app._get_current_object()
    return 'hello'
like image 187
gpasse Avatar answered Nov 15 '22 11:11

gpasse