无法使用flask.g访问其他函数中的变量

Raj*_*Raj 8 python flask

我试图用来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)

sou*_*kah 17

g对象是一个基于请求的对象,不会在请求之间保留,即g在您的请求index和请求之间重新创建get_posts.

应用程序Globals在Flask中:

Flask为您提供了一个特殊对象,确保它仅对活动请求有效,并为每个请求返回不同的值.简而言之:它做的是正确的,就像它对请求和会话一样.

对于在请求之间持久存储微小数据,请使用sessions.您可以(但不应该)app直接将数据存储在对象中以用于全局(所有会话)应用程序状态,类似于config如果您找到一个非常好的理由这样做的话.

对于更复杂的数据使用数据库.


Rac*_*ers 4

如果您需要跟踪身份验证信息,我建议使用 Flask 插件之一,例如Flask-LoginFlask-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 将神奇地随处可用。

我希望这有帮助!