【发布时间】:2019-02-11 20:11:13
【问题描述】:
干杯,伙计们,
重构我的 Flask 应用程序时,我被困在将 db 连接绑定到 @app.before_request 并在 @app.teardown_appcontext 处关闭它。我正在使用普通的 Psycopg2 和应用工厂模式。
首先我创建了一个在应用工厂中调用的函数,这样我就可以将@app 用作suggested by Miguel Grinberg here:
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
--
from shop.db import connect_and_close_db
connect_and_close_db(app)
--
return app
然后我尝试了http://flask.pocoo.org/docs/1.0/appcontext/#storing-data建议的这种模式:
def connect_and_close_db(app):
@app.before_request
def get_db_test():
conn_string = "dbname=testdb user=testuser password=test host=localhost"
if 'db' not in g:
g.db = psycopg2.connect(conn_string)
return g.db
@app.teardown_appcontext
def close_connection(exception):
db = g.pop('db', None)
if db is not None:
db.close()
结果:
TypeError: 'psycopg2.extensions.connection' object is not callable
有人知道发生了什么以及如何使其发挥作用吗?
此外,我想知道一旦创建游标绑定到before_request,我将如何访问连接对象以创建游标?
【问题讨论】:
-
你能告诉我们完整的追溯吗?