我正在尝试从 Flask 服务器将大型 CSV 流式传输到客户端,该服务器使用 Flask-SQLAlchemy。
配置应用程序时(使用工厂模式),每次请求后都会调用db.session.close()
:
@app.after_request
def close_connection(r):
db.session.close()
return r
到目前为止,此配置一直运行良好,因为所有请求都是短暂的。但是,当流式传输响应时,SQLAlchemy session 会提前关闭,在调用生成器时会抛出以下错误:
sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Question> is not bound to a Session; lazy load operation of attribute 'offered_answers' cannot proceed
伪代码:
@app.route('/export')
def export_data():
answers = Answer.query.all()
questions = Question.query.all()
def generate():
Iterate through answers questions and write out various relationships to csv
response = Response(stream_with_context(generate()), mimetype='text/csv')
return response
我尝试了使用/不使用 stream_with_context
和 def close_connection
中的全局标志的多种配置,以不自动关闭连接,但同样的错误仍然存在。
最佳答案
@app.after_request
在调用流式传输文件的生成器之前关闭数据库 session 。
解决方案是将db.session.close()
迁移到@app.teardown_request
。实例化 Response
时还必须使用 stream_with_context
。
关于python - 在流式传输 Flask 响应时保持 SQLAlchemy session 处于事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52957516/