Flask - g变量

传送门

  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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值