Django应用中如何正确与线程共享mysql.connector?
解决MySQL
commands out of sync错误:Django中线程安全的连接与游标管理 问题背景
此前通过__enter__和__exit__包装MySQL游标后,出现commands out of sync; you can't run this command now错误,还伴随退出码245的进程崩溃。原本以为Django依赖多进程实现并行处理,但打印Thread.ident和Thread.native_id时发现线程ID持续变化,于是尝试了线程绑定连接的方案。
已尝试的实现代码
线程绑定的连接获取函数
def db_connect(): t = threading.current_thread() if not hasattr(t, 'db_connection'): print(f"New MyDBConnectionClass for {t.ident}~{t.native_id}") t.db_connection = MyDBConnectionClass() return t.db_connection.get_cursor() # 该游标对象自带__exit__方法用于关闭游标
自定义数据库连接类
class MyDBConnectionClass(): def __del__(self): t = threading.current_thread() print(f"MyDBConnectionClass deleted for {t.ident}~{t.native_id}")
视图中的游标使用方式
with db_connect() as db: results = db.all(query, args)
当前状态与疑问
该方案暂时解决了commands out of sync错误和退出码245的崩溃问题,但存在以下困惑:
MyDBConnectionClass.__del__从未被触发,推测要么Thread对象未被销毁,要么有其他因素阻止了析构函数执行- 这个实现方式和查阅到的官方文档、示例代码不符
- 写法不够简洁,不符合Django的设计风格
目前推测应用存在线程池,之前的崩溃是因为请求有时在创建连接的线程中处理,有时切换到了其他线程,给每个线程分配独立连接的思路是有效的,但仍需解决上述问题。
核心需求
如何正确处理MySQL连接与游标对象,让我能在Django视图中自由使用如下写法:
with my_connection_wrapper.get_cursor() as my_cursor_wrapper: my_cursor_wrapper.foo()
同时避免资源泄漏,且不会出现线程亲和性不稳定的问题?
内容的提问来源于stack exchange,提问作者spraff
相关产品推荐
相关产品推荐

