1 回答

TA貢獻1865條經驗 獲得超7個贊
PyMSQL不允許線程共享同一個連接(模塊可以共享,但線程不能共享連接)。您的模型類在各處重用相同的連接。
因此,當不同的工作人員調用模型進行查詢時,他們使用相同的連接對象,從而導致沖突。
確保您的連接對象是線程本地的。不要使用db
類屬性,而是考慮一種檢索線程本地連接對象的方法,而不是重用可能在不同線程中創建的連接對象。
例如,在任務中創建連接。
現在,您在每個模型的任何地方都使用全局連接。
# Connect to the database
connection = pymysql.connect(**database_config)
class Model(object):
? ? """
? ? Base Model class, all other Models will inherit from this
? ? """
? ? db = connection
為了避免這種情況,您可以在方法中創建數據庫__init__......
class Model(object):
? ? """
? ? Base Model class, all other Models will inherit from this
? ? """
? ? def __init__(self, *args, **kwargs):
? ? ? ? self.db = pymysql.connect(**database_config)
但是,這可能不高效/不實用,因為 db 對象的每個實例都會創建一個會話。
為了改進這一點,您可以使用一種方法threading.local來將連接保持在線程本地。
class Model(object):
? ? """
? ? Base Model class, all other Models will inherit from this
? ? """
? ? _conn = threading.local()
? ? @property
? ? def db(self):
? ? ? ? if not hasattr(self._conn, 'db'):
? ? ? ? ? ? self._conn.db = pymysql.connect(**database_config)
? ? ? ? return self._conn.db
請注意,假設您使用線程并發模型,線程本地解決方案就可以工作。另請注意,celery 默認情況下使用多個進程(prefork)。這可能是問題,也可能不是問題。
添加回答
舉報