Flask

传送门

  1. http://flask.pocoo.org/docs/1.0/appcontext/#storing-data
  2. http://flask.pocoo.org/docs/1.0/appcontext
  3. http://flask.pocoo.org/docs/1.0/appcontext/#storing-data

概念

  1. It is a simple namespace object that has the same lifetime as an application context.
  2. The g name stands for “global”, but that is referring to the data being global within a context. 就是“局部”的全局变量(context的意思也是“局部”的“全局”)
  3. 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中“复用”。

原文地址:https://www.cnblogs.com/allen2333/p/9232869.html