码迷,mamicode.com
首页 > 其他好文 > 详细

Flask - g变量

时间:2018-06-27 11:26:36      阅读:1744      评论:0      收藏:0      [点我收藏+]

标签:mon   err   ase   text   not   lock   而且   变量   传送门   

传送门

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

Flask - g变量

标签:mon   err   ase   text   not   lock   而且   变量   传送门   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!