原文:我最近已經開始從我的一些舊的代碼,使MySQL OperationalErrors,似乎無法追溯的問題。既然它以前工作,我認爲它可能是一個軟件更新,打破了一些東西。我使用python 2.7與django runfcgi與nginx。這是我原來的代碼:Python和Django的OperationalError(2006年,「MySQL服務器已經走了」)
views.py
DBNAME = "test"
DBIP = "localhost"
DBUSER = "django"
DBPASS = "password"
db = MySQLdb.connect(DBIP,DBUSER,DBPASS,DBNAME)
cursor = db.cursor()
def list(request):
statement = "SELECT item from table where selected = 1"
cursor.execute(statement)
results = cursor.fetchall()
我曾嘗試以下,但它仍然不能正常工作:
views.py
class DB:
conn = None
DBNAME = "test"
DBIP = "localhost"
DBUSER = "django"
DBPASS = "password"
def connect(self):
self.conn = MySQLdb.connect(DBIP,DBUSER,DBPASS,DBNAME)
def cursor(self):
try:
return self.conn.cursor()
except (AttributeError, MySQLdb.OperationalError):
self.connect()
return self.conn.cursor()
db = DB()
cursor = db.cursor()
def list(request):
cursor = db.cursor()
statement = "SELECT item from table where selected = 1"
cursor.execute(statement)
results = cursor.fetchall()
目前,我唯一的解決方法是在使用mysql的每個函數中執行MySQLdb.connect()
。另外我注意到,當使用django的manage.py runserver
時,我不會遇到這個問題,而nginx會拋出這些錯誤。我懷疑我是否在連接超時,因爲list()
正在服務器啓動的幾秒內被調用。我使用的軟件是否有任何更新會導致此問題被破解/是否有解決方案?
編輯:我意識到,我最近寫了一篇中間件來守護進程的功能,這是問題的原因。但是,我無法弄清楚爲什麼。下面是中間件
def process_request_handler(sender, **kwargs):
t = threading.Thread(target=dispatch.execute,
args=[kwargs['nodes'],kwargs['callback']],
kwargs={})
t.setDaemon(True)
t.start()
return
process_request.connect(process_request_handler)
你有一個名爲'list'的本地函數?這是一個壞主意。 – hughdbrown
在某些數據庫適配器/庫中,有一個設置爲自動重新連接,類似於mysql客戶端如何處理超時。看看你是否可以設置它。 –