Skip to content

Instantly share code, notes, and snippets.

@geekKeen
Created July 25, 2017 08:04
Show Gist options
  • Save geekKeen/466b112993a5e3b37271317727867d9a to your computer and use it in GitHub Desktop.
Save geekKeen/466b112993a5e3b37271317727867d9a to your computer and use it in GitHub Desktop.
from flask import g
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = connect_to_database()
return db
@app.teardown_appcontext
def teardown(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
from werkzeug.local import LocalProxy
db = LocalProxy(get_db)
@geekKeen
Copy link
Author

geekKeen commented Jul 25, 2017

  1. app context 解决的是多个app直接在一个进程中跑的问题,那么在程序中如何获取所对应的 App
  2. 所以 app_context 是可以做一个 给每个请求做一个缓存,或者 每个请求共同使用的东西
  3. 注意 werkzeug 的用法, 通过这种方法,可以实现类似current_app 的功能, 隐式调用
  4. 所以 g 保存的是 app 的内容

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment