Flask, blue_print, current_app

I am trying to add a function to the jinja environment from blue print (the function that I will use in the 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) 

Then I can use this function in my template. I can’t understand how I can access the application since

 app = current_app._get_current_object() 

return error

 working outside of request context 

How can I implement such a template?

+7
source share
1 answer

The error message was pretty clear:

works out of context of request

In my project, I tried 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 just add to move the current_app statement to a function. Finally, it works like this:

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' 
+9
source

All Articles