什么时候应该使用Flask.g? [英] When should Flask.g be used?
问题描述
我看见 g
将从请求上下文移动到Flask 0.10中的应用上下文,这使我对 g
的使用感到困惑。
我对Flask 0.9的理解是:
$ b $ ul
$ g
存在于请求上下文中,即在请求开始时重新创建,并且直到它结束为止。
g
旨在被用作一个请求黑板,在这里我可以放置与请求持续时间有关的东西(即,在请求开始时设置一个标志并在最后处理它,可能来自 before_request
/ after_request
pair) g
可以并且应该用于资源管理,即保存数据库连接等。其中这些句子在Flask 0中不再是真的。 10?有人能指点我一个资源来讨论改变的原因吗?我应该使用Flask 0.10中的请求黑板 - 我应该创建自己的应用程序/扩展特定的线程本地代理,并将其推送到上下文堆栈 before_request
?在应用程序上下文中,如果我的应用程序长期存在(不像请求),资源永远不会被释放,那么在应用程序上下文中的资源管理又有什么意义呢?
Advanced Flask Patterns ,由Markus,解释了0.10中 g
的一些变化:
-
g
现在位于应用程序上下文中。 每个请求都会推送一个新的应用程序上下文,擦除旧的应用程序上下文,所以仍然可以使用g
来设置标志每个请求,而不会改变代码。 - 在调用
teardown_request
之后,应用程序上下文被弹出。 (Armin的演示文稿解释说,这是因为创建数据库连接是为请求环境设置的任务,不应在before_request
内处理,after_request
)
I saw that g
will move from the request context to the app context in Flask 0.10, which made me confused about the intended use of g
.
My understanding (for Flask 0.9) is that:
g
lives in the request context, i.e., created afresh when the requests starts, and available until it endsg
is intended to be used as a "request blackboard", where I can put stuff relevant for the duration of the request (i.e., set a flag at the beginning of the request and handle it at the end, possibly from abefore_request
/after_request
pair)- in addition to holding request-level-state,
g
can and should be used for resource management, i.e., holding database connections, etc.
Which of these sentences are no longer true in Flask 0.10? Can someone point me to a resource discussing the reasons for the change? What should I use as a "request blackboard" in Flask 0.10 - should I create my own app/extension specific thread-local proxy and push it to the context stack before_request
? What's the point of resource management at the application context, if my application lives for a long while (not like a request) and thus the resources are never freed?
Advanced Flask Patterns, as linked by Markus, explains some of the changes to g
in 0.10:
g
now lives in the application context.- Every request pushes a new application context, wiping the old one, so
g
can still be used to set flags per-request without change to code. - The application context is popped after
teardown_request
is called. (Armin's presentation explains this is because things like creating DB connections are tasks which setup the environment for the request, and should not be handled insidebefore_request
andafter_request
)
这篇关于什么时候应该使用Flask.g?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!