問題原因:
由于資料庫wait_timeout逾時.
set global wait_timeout=10;
解決辦法:
在settings中加入:
from django.db.models.sql.compiler import SQLCompiler
from django.db.models.sql.constants import MULTI, GET_ITERATOR_CHUNK_SIZE
from django.db import connection, OperationalError
def is_connection_usable():
try:
connection.connection.ping()
except:
return False
else:
return True
def my_execute_sql(self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE):
# 需要注意的是: connection會自動連接配接,是以隻需要關閉即可
"""
def _cursor(self, name=None):
self.ensure_connection()
with self.wrap_database_errors:
return self._prepare_cursor(self.create_cursor(name))
"""
for i in range(2):
try:
res = default_execute_sql(self, result_type, chunked_fetch, chunk_size)
return res
except OperationalError as e:
# traceback.print_exc()
print("資料庫錯誤!", i, e)
self.connection.close()
# if not is_connection_usable():
# connection.close()
default_execute_sql = SQLCompiler.execute_sql
SQLCompiler.execute_sql = my_execute_sql