我试图用来flask.g存储可以在其他函数中访问的变量,但我似乎没有正确地做某事.当我尝试访问时,应用程序生成以下错误g.name: AttributeError: '_RequestGlobals' object has no attribute 'name'.
该文档的flask.g说:
只要存储在你想要的任何东西上.例如,数据库连接或当前登录的用户.
这是一个完整的,最小的例子,它说明了我在尝试访问创建函数之外的变量时收到的错误.任何帮助都将非常感激.
#!/usr/bin/env python
from flask import Flask, render_template_string, request, redirect, url_for, g
from wtforms import Form, TextField
application = app = Flask('wsgi')
@app.route('/', methods=['GET', 'POST'])
def index():
form = LoginForm(request.form)
if request.method == 'POST' and form.validate():
name = form.name.data
g.name = name
# Need to create an instance of a class and access that in another route
#g.api = CustomApi(name)
return redirect(url_for('get_posts'))
else:
return render_template_string(template_form, form=form)
@app.route('/posts', methods=['GET'])
def get_posts():
# Need to access the instance of CustomApi here
#api = g.api
name = g.name
return render_template_string(name_template, name=name)
class LoginForm(Form):
name = TextField('Name')
template_form = """
{% block content %}
<h1>Enter your name</h1>
<form method="POST" action="/">
<div>{{ form.name.label }} {{ form.name() }}</div><br>
<button type="submit" class="btn">Submit</button>
</form>
{% endblock %}
"""
name_template = """
{% block content %}
<div>"Hello {{ name }}"</div><br>
{% endblock %}
"""
if __name__ == '__main__':
app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)
如果您需要跟踪身份验证信息,我建议使用 Flask 插件之一,例如Flask-Login或Flask-Principal。
例如,我们使用 Flask-Principal。当有人进行身份验证(或检测到身份验证 cookie)时,它会引发身份加载信号。然后,我们将他们的登录身份映射到我们数据库中的用户。像这样的东西:
# not actual code
@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
user = Person.query.filter(Person.username==identity.person.username).one()
g.user = user
Run Code Online (Sandbox Code Playgroud)
然后我们可以在任何控制器或模板中使用 g.user 。(我们实际上删除了很多内容,这是一个简单、懒惰的黑客行为,但造成的麻烦比其价值更多。)
如果您不想使用模块,可以在每个请求开始时连接一个内置信号:
http://flask.pocoo.org/docs/tutorial/dbcon/
# This runs before every request
@app.before_request
def before_request():
g.user = your_magic_user_function()
Run Code Online (Sandbox Code Playgroud)
然后 g.user 将神奇地随处可用。
我希望这有帮助!