在烧瓶应用程序中保留全局状态 [英] Preserving global state in a flask application
问题描述
我正在尝试在我的 flask
应用程序中保存一个缓存字典.
I am trying to save a cache dictionary in my flask
application.
据我所知,应用上下文,尤其是flask.g 对象 应该用于此.
As far as I understand it, the Application Context, in particular the flask.g object should be used for this.
设置:
import flask as f
app = f.Flask(__name__)
现在如果我这样做:
with app.app_context():
f.g.foo = "bar"
print f.g.foo
它打印bar
.
继续以下内容:
with app.app_context():
print f.g.foo
AttributeError: '_AppCtxGlobals' object has no attribute 'foo'
我不明白,文档根本没有帮助.如果我正确阅读它们,状态应该被保留.
I don’t understand it and the docs are not helping at all. If I read them correctly the state should have been preserved.
另一个想法我只是简单地使用模块范围的变量:
Another idea I had was to simply use module-wide variables:
cache = {}
def some_function():
cache['foo'] = "bar"
但似乎每次请求都会重置这些.
But it seems like these get reset with every request.
如何正确执行此操作?
Flask 10.1
Flask 10.1
推荐答案
根据您的问题,我认为您对全局"的定义感到困惑.
Based on your question, I think you're confused about the definition of "global".
在现有的 Flask 设置中,您有一个 Flask 服务器,其中包含多个线程和潜在的多个处理请求的进程.假设您有一个像itemlist = []"这样的常用全局变量,并且您想在每个请求中不断添加它 - 例如,每次有人向端点发出 POST 请求时.这在理论上和实践上都是完全可能的.这也是一个非常糟糕的主意.
In a stock Flask setup, you have a Flask server with multiple threads and potentially multiple processes handling requests. Suppose you had a stock global variable like "itemlist = []", and you wanted to keep adding to it in every request - say, every time someone made a POST request to an endpoint. This is totally possible in theory and practice. It's also a really bad idea.
问题是您无法轻松控制哪些线程和进程获胜"——该列表可能以非常不稳定的顺序排列,或者完全损坏.所以现在您需要讨论锁、互斥锁和其他原语.这既困难又烦人.
The problem is that you can't easily control which threads and processes "win" - the list could up in a really wonky order, or get corrupted entirely. So now you need to talk about locks, mutexs, and other primitives. This is hard and annoying.
您应该使网络服务器本身尽可能无状态.每个请求应该是完全独立的,并且不共享服务器中的任何状态.相反,使用将为您处理状态的数据库或缓存层.这看起来更复杂,但实际上更简单.以 SQLite 为例;很简单.
You should keep the webserver itself as stateless as possible. Each request should be totally independent and not share any state in the server. Instead, use a database or caching layer which will handle the state for you. This seems more complicated but is actually simpler in practice. Check out SQLite for example ; it's pretty simple.
为了解决flask.g"对象,它是一个基于每个请求的全局对象.
To address the 'flask.g' object, that is a global object on a per request basis.
http://flask.pocoo.org/docs/api/#flask.g
它在请求之间被清除干净",不能用于在它们之间共享状态.
It's "wiped clean" between requests and cannot be used to share state between them.
这篇关于在烧瓶应用程序中保留全局状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!