flask实现mysql连接池_python flask出现数据库连接池异常的处理过程

在使用Flask进行开发时,遇到了`sqlalchemy session pool overflow`异常。通过调整数据库连接池大小、使用locust进行压力测试,发现问题是由于未正确释放数据库连接导致。解决方法是在`app.teardown_appcontext`中调用`db_session.remove()`,关闭`app.debug`模式,确保每次请求结束后都能清理连接池。遵循这些调整后,异常不再出现。
摘要由CSDN通过智能技术生成

在测试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会引起某些程序行为和正式运行时有些不同。需要留意这一点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值