【发布时间】:2018-06-09 19:32:02
【问题描述】:
请求处理后如何使用 after_request 装饰器关闭连接?我使用 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 装饰器?我无法真正遵循文档 确切的代码会对我有所帮助。
【问题讨论】:
-
在
categories_list中使用conn不会抛出任何错误? -
@GarbageCollector 有一个 before_request,除了我在 init.py 中使用过之外它没有
-
可以使用flask.g创建全局数据库连接对象。
-
我想我在这里找到了一些东西:stackoverflow.com/questions/16311974/…
标签: python postgresql flask sqlalchemy