g 对象也就是global 全局对象,可以用于存放开发者自己定义的一些数据,在整个request生命周期内生效。
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一般用来传递上下文的数据,flask里面有很多钩子函数,例如before_first_request之类的,g提供了一个方法将数据共享到正常的路由函数里去。 举个例子,你可以在before_request里面做Http Basic Authentication验证,然后将验证过的用户数据存在g里面,这样在路由函数里就可以直接调用g里面的用户数据了,而不用再搞个全局变量。这样非常方便
g对象是在整个flask应用运行期间都是可以使用的,并且也是和request一样,是线程隔离的
from flask import Flask, request, g
app = Flask(__name__)
def is_admin():
if g.user == 'admin':
return True
else:
return False
@app.route('/login')
def login():
user = request.args.get('username')
g.user = user
if is_admin():
return {'msg': 'ok', 'admin': 'yes'}
else:
return {'msg': 'ok', 'admin': 'no'}
if __name__ == '__main__':
app.run()
g对象的出现,让你在任何位置都能获得用户数据,避免了在函数参数里传递这些数据。
上面代码其实等价于
def is_admin(user):
if user == 'admin':
return True
else:
return False
@app.route('/login')
def login():
user = request.args.get('username')
if is_admin(user):
return {'msg': 'ok', 'admin': 'yes'}
else:
return {'msg': 'ok', 'admin': 'no'}
g对象有个好处是,当函数写在其它模块的时候,不需要导入这个模块(避免循环导入问题)
g对象的生命周期
g对象和session的区别
也就是说session可以在我们的这个网站随意都可以用 而 g 只能是这次的请求如果重定向之后就会改变。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有