直接上代码:
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)
参考资料:
http://luruoyu.blog.51cto.com/2876338/788315
https://code.djangoproject.com/ticket/21597
http://stackoverflow.com/questions/14163429/python-and-django-operationalerror-2006-mysql-server-has-gone-away
http://stackoverflow.com/questions/7835272/django-operationalerror-2006-mysql-server-has-gone-away
https://github.com/celery/django-celery/issues/359