diff --git a/django_mysqlpool/backends/mysqlpool/base.py b/django_mysqlpool/backends/mysqlpool/base.py index bbcba95..8bc5cba 100644 --- a/django_mysqlpool/backends/mysqlpool/base.py +++ b/django_mysqlpool/backends/mysqlpool/base.py @@ -16,7 +16,8 @@ # Needs to be less than MySQL connection timeout (server setting). The default is 120, # so default to 119. MYSQLPOOL_TIMEOUT = 119 - +# Times to try reconnecting to the database if the connection goes stale in the pool +MYSQLPOOL_RETRY = 5 def isiterable(value): "Checks if the provided value is iterable." @@ -57,9 +58,11 @@ def __hash__(self): def get_pool(): "Creates one and only one pool using the configured settings." global MYSQLPOOL + global MYSQLPOOL_RETRY if MYSQLPOOL is None: backend = getattr(settings, 'MYSQLPOOL_BACKEND', MYSQLPOOL_BACKEND) backend = getattr(pool, backend) + MYSQLPOOL_RETRY = getattr(settings, 'MYSQLPOOL_RETRY', MYSQLPOOL_RETRY) kwargs = getattr(settings, 'MYSQLPOOL_ARGUMENTS', {}) kwargs.setdefault('poolclass', backend) # The user can override this, but set it by default for safety. @@ -81,7 +84,18 @@ def connect(**kwargs): # compatible with their serialization. kwargs['conv'] = HashableDict(conv) # Open the connection via the pool. - return get_pool().connect(**kwargs) + retry = MYSQLPOOL_RETRY + connection = None + while(retry and not connection): + try: + connection = get_pool().connect(**kwargs) + except: + connection = None + retry -= 1 + if connection: + return connection + else: + return get_pool().connect(**kwargs) # Monkey-patch the regular mysql backend to use our hacked-up connect() function.