在测试flask程序时,出现异常
sqlalchemy session pool over flow
第一次见到问题,手工操作无法重现。
在网上查到有类似的处理
In multi-thread mode, if your concurrent request num is much more than the db connection pool size, it will throw the Queue Pool limit of size 5 overflow 10 reached error. try with this:
engine = create_engine('mysql://', convert_unicode=True,
pool_size=20, max_overflow=100)
to add the pool size
Add: the method above is not a correct way. The actual reason is that db connection pool is used up, and no other available connection. The most probably situation is you miss to release connection. For example:
参考网上资料,自己用locust做大量连接测试,重现一次,从运行记录看,似乎和发生了异常有关。
为了确认,专门做了一个函数,这个函数什么也不做,只是抛出异常。结果,locust只是执行了几
十次连接以后,就开始重现前面所说的session poll异常。非常准确。
问题清楚了,剩下的事情变得简单。把after_request过程里的session.remove调用放到
app.shutdown_context过程里。再把app.debug关掉。
此时再启动locust测试,执行连接4000次,session pool异常再也没出现。
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
参考链接
http://www.karoltomala.com/blog/?p=579
http://gexp.iteye.com/blog/737408
https://www.gaott.info/sqlalchemy-auto-commit/
这个比较重要:
https://github.com/mitsuhiko/flask/issues/661
这个问题的要点:
1 必须在app.teardown_appcontext过程,释放session
2 应当将app.debug=True关掉。在此开关打开的情况下,如果发生异常,
app.teardown_appcontext不到保证得到执行,则session pool很快就会耗尽。以后的数据库
访问操作任何操作都会遇到前面所说的异常。
结论
1 session的remove调用,不应在after_request过程中执行,而是在app.teardown_appcontext过程中执行。
2 注意app.debug=True会引起某些程序行为和正式运行时有些不同。需要留意这一点。