Flask - g变量
Posted allen2333
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask - g变量相关的知识,希望对你有一定的参考价值。
传送门
- http://flask.pocoo.org/docs/1.0/appcontext/#storing-data
- http://flask.pocoo.org/docs/1.0/appcontext
- http://flask.pocoo.org/docs/1.0/appcontext/#storing-data
概念
- It is a simple namespace object that has the same lifetime as an application context.
- The g name stands for “global”, but that is referring to the data being global within a context. 就是“局部”的全局变量(context的意思也是“局部”的“全局”)
- The application context is a good place to store common data during a request or CLI command. (每个请求到来都会push application context和request context到Local Stack. Context which in Flask is defined as being either a thread, process or greenlet.)
A common use for g is to manage resources during a request.
from flask import g
def get_db():
if ‘db‘ not in g:
g.db = connect_to_database()
return g.db
@app.teardown_appcontext
def teardown_db():
db = g.pop(‘db‘, None)
if db is not None:
db.close()
在同一个request里,用get_db得到的都是同一个数据库连接,而且在request的最后会自动关闭连接。这就可以在一个request中“复用”。
以上是关于Flask - g变量的主要内容,如果未能解决你的问题,请参考以下文章
Flask中g对象,以及g,session,flash之间的区别
Flask 框架中 上下文基础理念,包括cookie,session存储方法,requset属性,current_app模块和g模块