標籤:django mysql gone 連結
有個django的定時任務,調用django的orm來對資料庫進行資料處理。 在互動環境下直接啟動pyhton指令碼沒有問題,放在定時任務中時候,總是出現
(2006, ‘MySQL server has gone away‘)
的錯誤,開始以為是定時架構外部調用的問題,但是後來想想也不合理,為啥直接在shell中調用就沒錯呢,想到django1.6的一些資料庫連接的新屬性(例如持久化串連等)會不會有影響,於是google了下。
看到django官網上有人提過這個類似於bug的東西:https://code.djangoproject.com/ticket/21597
如果單純的查詢這個資料庫錯誤,很多都是讓你修改mysql的配置,看下這裡最終給的建議把。
If you hit this problem and don‘t want to understand what‘s going on, don‘t reopen this ticket, just do this:
- RECOMMENDED SOLUTION: close the connection with from django.db import connection; connection.close() when you know that your program is going to be idle for a long time.
- CRAPPY SOLUTION: increase wait_timeout so it‘s longer than the maximum idle time of your program.
In this context, idle time is the time between two successive database queries.
這個方案就說把django到mysql的資料庫連接關閉了,然後重建立立一個來查詢,如果想瞭解下為什麼,可以重頭看下這討論。
from django.db import connection...def is_connection_usable(): try: connection.connection.ping() except: return False else: return True... def do_work(): while(True): # Endless loop that keeps the worker going (simplified) if not is_connection_usable(): connection.close() try: do_a_bit_of_work() except: logger.exception("Something bad happened, trying again") sleep(1)
簡單的理解,就是django1.6 會自動保持串連, 因為我這個任務時24小時執行一次, 第一執行的時候django和mysql建立的一個連結A, 結果這個任務10分鐘就完成了,串連A開始睡眠,django繼續保持這串連。
23小時50分鐘以後,這個任務又開始執行了,但是由於msyql的waittime預設是8個小時,串連A這個時候已經死了(msyql單方面解除合約,django還蒙在鼓裡),django還用串連A去串連mysql,肯定得到一個gone away的結果。
所有我們在每次執行任務之前去檢查串連是否存活,如果沒了那麼就close,django自動重建立立一個,這樣就消除了上面的錯誤。
本文出自 “orangleliu筆記本” 部落格,轉載請務必保留此出處http://blog.csdn.net/orangleliu/article/details/41480417
作者orangleliu 採用署名-非商業性使用-相同方式共用協議
[django1.6]跑批任務錯誤(2006, 'MySQL server has gone away')