什么时候应该使用 Flask.g? [英] When should Flask.g be used?

查看:27
本文介绍了什么时候应该使用 Flask.g?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到 g 将从Flask 0.10 中应用上下文的请求上下文,这让我对 g 的预期用途感到困惑.

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.

我的理解(对于 Flask 0.9)是:

My understanding (for Flask 0.9) is that:

  • g 存在于请求上下文中,即在请求开始时重新创建,并在请求结束时可用
  • g 旨在用作请求黑板",我可以在其中放置与请求持续时间相关的内容(即,在请求的开头设置一个标志并处理它)最后,可能来自 before_request/after_request 对)
  • 除了保持请求级状态之外,g 可以而且应该用于资源管理,即保持数据库连接等.
  • g lives in the request context, i.e., created afresh when the requests starts, and available until it ends
  • g 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 a before_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.

以下哪些句子在 Flask 0.10 中不再正确?有人可以向我指出讨论更改原因的资源吗?我应该在 Flask 0.10 中使用什么作为请求黑板"——我应该创建自己的应用程序/扩展特定的线程本地代理并将其推送到上下文堆栈 before_request 吗?如果我的应用程序存在很长时间(不像请求)并且资源永远不会被释放,那么在应用程序上下文中进行资源管理有什么意义?

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?

推荐答案

高级烧瓶模式,正如 由 Markus 链接,解释了一些0.10 中对 g 的更改:

Advanced Flask Patterns, as linked by Markus, explains some of the changes to g in 0.10:

  • g 现在存在于应用程序上下文中.
  • 每个请求都会推送一个新的应用程序上下文,擦除旧的,所以 g 仍然可以用于设置每个请求的标志,而无需更改代码.
  • 应用上下文在 teardown_request 被调用后弹出.(Armin 的演示解释了这是因为像创建数据库连接这样的事情是设置请求环境的任务,不应在 before_requestafter_request)
  • 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 inside before_request and after_request)

这篇关于什么时候应该使用 Flask.g?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆