天天看点

django.db.utils.OperationalError: (2006, “MySQL server has gone away 104, ‘Connection reset by peer‘

问题原因:

由于数据库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