Question
https://stackoverflow.com/questions/39480914/why-db-session-remove-must-be-called
Xnip2018-08-08_10-40-57.jpg
Answer
Xnip2018-08-08_10-41-11.jpg
译文
Using the above flow, the process of integrating the Session with the web application has exactly two requirements:
Ensure that scoped_session.remove() is called when the web request ends,
usually by integrating with the web framework’s event system to establish an “on request end” event.
在sqlalchemy中,scoped_session.remove()操作之所以要被提及,
是因为web应用中的session应该是scoped类型的session,
也就是说应用中每个 request handler都会自主创建及销毁自己的session。
这一点非常有必要,因为服务器一般都是多进程的,会同时处理多个请求,每个请求使用的都是不同的session。
这个自动remove的方案被flask_sqlalchemy 完美解决:对于每个请求,它会创建一个新的scoped session。
在flask >=0.9 版本中,通过在app.teardown_appcontext中安装了一个hook机制,
具体请看这里https://github.com/mitsuhiko/flask-sqlalchemy/blob/master/flask_sqlalchemy/init.py#L819
在单元测试的环境中,你其实并没有完全复现真实的请求情景,因为没有应用上下文的push/pop操作。
这样的话,在请求的最后也并没有执行db.session.remove()动作。
同样的还有,哪些在before_request 和 after_request 中的函数。
你可以通过在测试中加入下面的改动:
def test_foo(self):
with app.app_context():
client = app.test_client()
# do testing here for your endpoints
有了上面代码的话,就不再需要每次再写remove操作了。
Flask-Testin的文档似乎已经很久没有人维护了,也行有时候会worked,但是对于当前的flask和flask_sqlalchemy版本匹配不上。
网友评论