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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值