Django 1.6 中的 connection.cursor() 线程安全吗?

osm*_*man 2 python django cursor multiprocessing django-database

AFAIK 在 Django 1.6 中,游标在请求之间共享,并在需要时打开一个新连接。但是,我找不到有关 connection.cursor() 方法如何工作以及如何在文档中的不同进程中使用 connection.cursor() 方法的任何信息。

我见过的大多数代码都没有关闭从 connection.cursor() 返回的游标对象,所以我假设 Django 在请求完成时自动关闭从 connection.cursor() 返回的游标对象,但是如果我调用 connection.cursor() 呢? ) 在不同的过程中?我应该在终止进程时关闭该游标还是游标的包装函数自动杀死自己?

alk*_*lko 5

线程安全取决于数据库连接的实现,可能的情况参见Python 数据库 API 规范 v2.0

threadsafety:表示接口支持的线程安全级别的整数常量。可能的值为:

threadsafety  Meaning
0             Threads may not share the module.
1             Threads may share the module, but not connections.
2             Threads may share the module and connections.
3             Threads may share the module, connections and cursors.
Run Code Online (Sandbox Code Playgroud)

例如,MySQL、PostgreSQL 和 Oracle:

>>> import MySQLdb
>>> MySQLdb.threadsafety
1
>>> import psycopg2
>>> psycopg2.threadsafety
2
>>> import cx_Oracle
>>> cx_Oracle.threadsafety
2
Run Code Online (Sandbox Code Playgroud)

因此,似乎没有 Django 支持的数据库连接在游标级别是线程安全的。

通常,游标是用__del__方法关闭的,即当垃圾收集时,或者当线程正常终止时(与它被杀死时相反,因为守护线程可能会结束)。我记得在特定平台上处理游标的一些错误,即 oracle 著名ORA-01000 Too many cursors错误的一些问题。快速谷歌搜索发现Jython 的一个错误,但我很确定我在 CPython 中也有问题。另见这张票