2012-03-30 148 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'