传送门
- 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中“复用”。