2012-03-30 16 views
7

Próbuję dodać funkcję w środowisku jinja z niebieskiego wydruku (funkcja, której użyję do szablonu).Flask, blue_print, current_app

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) 

Teraz w MyBluePrint.py, chciałbym dodać coś takiego:

def role_function(): 
    return 'admin' 
app.jinja_env.globals.update(role_function=role_function) 

Będę mógł wtedy użyć tej funkcji w moim szablonie. Nie mogę dowiedzieć się, w jaki sposób mogę uzyskać dostęp do aplikacji, ponieważ

app = current_app._get_current_object() 

zamian Błąd

working outside of request context 

Jak mogę wdrożyć taki wzór?

Odpowiedz

9

Błąd wiadomość faktycznie dość jasne:

pracy poza kontekstem żądanie

W moim planem, starałem się dostać mój wniosek poza funkcją „request”:

heysyni = Blueprint('heysyni', __name__) 

app = current_app._get_current_object() 
print app 

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

Po prostu dodajemy do przeniesienia instrukcji current_app do funkcji. Wreszcie to działa w ten sposób:

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'