如何使用after_request decorator在处理请求后关闭连接?我使用before_request打开每个api请求的连接,如下所示: 使用sqlalchemy core 1.0.8和postgresql 9.5:
#engine = create_engine(os.environ.get("DB_URL"))
DB_URL="postgresql://mowner:passwd@localhost/mydb"
@app.before_request
def before_request():
engine = create_engine(DB_URL, strategy='threadlocal')
conn = engine.connect()
@app.after_request
def after_request(conn):
if conn is not None:
print 'closing connection'
conn.close()
示例api电话:
@app.route('/api/v1.0/categories', methods=['GET'])
def categories_list():
'''
Return categories list
'''
if 'id' in session:
categories_list = []
s = select([categories])
rs = conn.execute(s)
if rs.rowcount > 0:
for r in rs:
categories_list.append(dict(r))
rs.close()
# print 'this doesnt execute'
return jsonify({'categories list': categories_list}), 200
return jsonify({'message': "UNAUTHORIZED"}), 401
视图是api调用,它只返回对象列表,添加或编辑对象和消息。如何将连接对象传递给after_request装饰器?我无法真正遵循文档 确切的代码可以帮助我。
答案 0 :(得分:4)
您可以使用flask.g来引用创建全局数据库连接对象并在任何地方使用
from flask import Flask, g
#engine = create_engine(os.environ.get("DB_URL"))
DB_URL="postgresql://mowner:passwd@localhost/mydb"
@app.before_request
def before_request():
engine = create_engine(DB_URL, strategy='threadlocal')
conn = engine.connect()
g.db = conn
然后在你的路线中使用连接
@app.route('/api/v1.0/categories', methods=['GET'])
def categories_list():
'''
Return categories list
'''
if 'id' in session:
categories_list = []
s = select([categories])
rs = g.db.execute(s) # change in variable
if rs.rowcount > 0:
for r in rs:
categories_list.append(dict(r))
rs.close()
# print 'this doesnt execute'
return jsonify({'categories list': categories_list}), 200
return jsonify({'message': "UNAUTHORIZED"}), 401
然后最后关闭它:
@app.after_request
def after_request(response):
if g.db is not None:
print 'closing connection'
g.db.close()
return response