sqlalchemy强制所有连接关闭mysql [英] sqlalchemy force all connections to close mysql

查看:301
本文介绍了sqlalchemy强制所有连接关闭mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在一些复杂的单元测试中使用sqlalchemy.在每次测试结束时,我们完全使用drop_all拆除数据库.有时,有人忘记关闭嵌入在单元测试中的会话.然后,我们必须花费大量时间来尝试找出问题所在,并最终关闭sqlalchemy会话.

We use sqlalchemy in some complicated unit tests. At the end of each test, we tear down the database entirely using drop_all. Now and then, someone forgets to close a session embedded deep inside a unit test. We then have to spend a fair amount of time trying to figure out just what is going wrong, and ultimately to close the sqlalchemy session.

我们想要一种可靠的方法来强制关闭与数据库的所有连接.我们已经尝试过session.close_all(),但这没有达到我的描述.

We want a want to reliably way to force all the connections to the database to close. We have tried session.close_all(), but this did not do what I describe.

下面是mysql进程列表,当进程挂起尝试删除数据库时,我们会看到它.大概ID 285是令人讨厌的过程:

Below is the mysql processlist we see when the process hangs attempting to drop the database. Presumably Id 285 is the offending process:

+-----+------+-----------------+----------+---------+------+---------------------------------+------------------------------+
| Id  | User | Host            | db       | Command | Time | State                           | Info                         |
+-----+------+-----------------+----------+---------+------+---------------------------------+------------------------------+
| 172 | root | localhost       | mydb     | Query   |    0 | init                            | show processlist             |
| 285 | root | localhost:47147 | mydb     | Sleep   |    6 |                                 | NULL                         |
| 289 | root | localhost:47152 | mydb     | Query   |    5 | Waiting for table metadata lock | DROP TABLE `mytable`         |
+-----+------+-----------------+----------+---------+------+---------------------------------+------------------------------+

每个请求中,我还包括事务日志:

Per request, I am also including the transaction log:

------------
TRANSACTIONS
------------
Trx id counter 1144929
Purge done for trx's n:o < 1144827 undo n:o < 0 state: running but idle
History list length 398
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0, not started
MySQL thread id 37, OS thread handle 0x8f46bb40, query id 776 localhost root init
show engine innodb status
---TRANSACTION 0, not started
MySQL thread id 45, OS thread handle 0x8f2ceb40, query id 774 localhost 127.0.0.1 root Waiting for table metadata lock
DROP TABLE `mytable`
---TRANSACTION 1144823, ACTIVE 12 sec
MySQL thread id 41, OS thread handle 0x8f2ffb40, query id 595 localhost 127.0.0.1 root cleaning up
Trx read view will not see trx with id >= 1144824, sees < 1144824

推荐答案

在烧瓶中,这应该可以解决问题:

In flask, this should do the trick:

@app.teardown_appcontext
def teardown_db(exception):
    db.session.commit()
    db.session.close()

这篇关于sqlalchemy强制所有连接关闭mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆