2012-03-30 151 views
7

我想從藍色打印(我將用於模板的函數)在忍者環境中添加一個函數。燒瓶,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) 

現在MyBluePrint.py,我想補充一點,如:

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

然後我可以在我的模板中使用這個功能。我想不通我怎麼能因爲

app = current_app._get_current_object() 

返回錯誤

working outside of request context 

我如何能實現這樣的模式訪問應用程序?

回答

9

消息錯誤實際上是相當清楚的:

請求上下文

在我的藍圖之外的工作,我試圖讓我的「請求」功能之外的應用:

heysyni = Blueprint('heysyni', __name__) 

app = current_app._get_current_object() 
print app 

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

我只是添加到將current_app語句移動到函數。最後,它的工作原理是這樣:

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'