Python and Django OperationalError (2006, 'MySQL server has gone away')

后端 未结 12 1726
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 15:25

Original: I have recently started getting MySQL OperationalErrors from some of my old code and cannot seem to trace back the problem. Since it was working before, I thought

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 16:13

    I've been struggling with this issue too. I don't like the idea of increasing timeout on mysqlserver. Autoreconnect with CONNECTION_MAX_AGE doesn't work either as it was mentioned. Unfortunately I ended up with wrapping every method that queries the database like this

    def do_db( callback, *arg, **args):
        try:
            return callback(*arg, **args)
        except (OperationalError, InterfaceError) as e:  # Connection has gone away, fiter it with message or error code if you could catch another errors
            connection.close()
            return callback(*arg, **args)
    
    do_db(User.objects.get, id=123)  # instead of User.objects.get(id=123)
    

    As you can see I rather prefer catching the exception than pinging the database every time before querying it. Because catching an exception is a rare case. I would expect django to reconnect automatically but they seemed to refused that issue.

提交回复
热议问题