FlaskG可变简单examp

2024-04-24 08:20:49 发布

您现在位置:Python中文网/ 问答频道 /正文

据我所知,g变量是从一个请求到另一个请求的临时存储器。例如,我认为它应该这样工作。但我不能让它工作。

from flask import Flask, g, redirect, url_for
app = Flask(__name__)

@app.route('/')
def hello_world():
    g = "hello world"
    return redirect(url_for('test'))

@app.route('/test')
def test():
    return str(g)

if __name__ == "__main__":
    app.run(debug=True)

Tags: namefromtestappurlflaskhellofor
1条回答
网友
1楼 · 发布于 2024-04-24 08:20:49

Flaskg在应用程序上下文中可用,并持续请求的生存期。

What is application context?

Application Context Page所述,烧瓶应用程序在执行时处于许多状态。

One of the design ideas behind Flask is that there are two different “states” in which code is executed. The application setup state in which the application implicitly is on the module level. It starts when the Flask object is instantiated, and it implicitly ends when the first request comes in. While the application is in this state a few assumptions are true:

  • the programmer can modify the application object safely.
  • no request handling happened so far
  • you have to have a reference to the application object in order to modify it, there is no magic proxy that can give you a reference to the application object you’re currently creating or modifying.

In contrast, during request handling, a couple of other rules exist:

  • while a request is active, the context local objects (flask.request and others) point to the current request.
  • any code can get hold of these objects at any time.

There is a third state which is sitting in between a little bit. Sometimes you are dealing with an application in a way that is similar to how you interact with applications during request handling; just that there is no request active. Consider, for instance, that you’re sitting in an interactive Python shell and interacting with the application, or a command line application.

所以,基本上,当你运行应用程序时,它会在许多州退出。

一个是满足您的请求,另一个是监视要重新加载的文件。

如果您曾经使用过Celery,那么您必须在单独的应用程序上下文中运行它。这就是g的角色发挥作用的时候。 芹菜的一个非常常见的用法是异步发送邮件。 假设您捕捉到一个请求,并且在处理它之后需要发送一封邮件。 您可以将用户信息存储在g中以传递给芹菜。

相关问题 更多 >