前言
g 对象也就是global 全局对象,可以用于存放开发者自己定义的一些数据,在整个request生命周期内生效。
g 对象讲解
g 也是我们常用的几个全局变量之一。在最开始这个变量是挂载在 Request Context 下的。但是在 0.10 以后,g 就是挂载在 App Context 下的。
首先,说一下 g 用来干什么,官方在上下文这一张里有这一段说明
The application context is created and destroyed as necessary. It never moves between threads and it will not be shared between requests. As such it is the perfect place to store database connection information and other things. The internal stack object is called flask.appctx_stack. Extensions are free to store additional information on the topmost level, assuming they pick a sufficiently unique name and should put their information there, instead of on the flask.g object which is reserved for user code.
g 保存的是当前请求的全局变量,不同的请求会有不同的全局变量,通过不同的thread id区别.
像数据库配置这样重要的信息挂载在app对象上,一些用户相关的数据,就可以挂载在g对象上,这样就不需要在函数里一层层传递。
g一般用来传递