gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:03:43 25 4
gpt4 key购买 nike

我正在尝试使用 flask.g 来存储可以在其他函数中访问的变量,但我似乎没有做正确的事情。当我尝试访问 g.name 时,应用程序生成以下错误:AttributeError: '_RequestGlobals' object has no attribute 'name'

documentation对于 flask.g 说:

Just store on this whatever you want. For example a database connection or the user that is currently logged in.

这是一个完整的最小示例,它说明了我在尝试访问创建它的函数之外的变量时收到的错误。我们将不胜感激任何帮助。

#!/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)

最佳答案

g 对象是一个基于请求的对象,不会在请求之间持续存在,即 g 在您对 index 的请求和您对 get_posts 的请求。

Application Globals in Flask :

Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request. In a nutshell: it does the right thing, like it does for request and session.

要在请求之间持久存储微小数据,请使用 sessions反而。如果您发现这是一个很好的理由。

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

关于python - 无法使用 flask.g 访问其他函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13757399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com