Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow setting max retries on the settings #39

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions django_dbconn_retry/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from django.db import utils as django_db_utils
from django.db.backends.base import base as django_db_base
from django.dispatch import Signal
from django.conf import settings

from typing import Union, Tuple, Callable, List # noqa. flake8 #118

Expand Down Expand Up @@ -51,15 +52,18 @@ def ensure_connection_with_retries(self: django_db_base.BaseDatabaseWrapper) ->
self.connect()
except Exception as e:
if isinstance(e, _operror_types):
if hasattr(self, "_connection_retries") and self._connection_retries >= 1:
if hasattr(self, "_connection_retries") and self._connection_retries >= getattr(settings, "MAX_DBCONN_RETRIES", 1):
_log.error("Reconnecting to the database didn't help %s", str(e))
del self._in_connecting
post_reconnect.send(self.__class__, dbwrapper=self)
raise
else:
_log.info("Database connection failed. Refreshing...")
# mark the retry
self._connection_retries = 1
if not hasattr(self, "_connection_retries"):
self._connection_retries = 0

self._connection_retries += 1
# ensure that we retry the connection. Sometimes .closed isn't set correctly.
self.connection = None
del self._in_connecting
Expand All @@ -69,8 +73,7 @@ def ensure_connection_with_retries(self: django_db_base.BaseDatabaseWrapper) ->
self.ensure_connection()
post_reconnect.send(self.__class__, dbwrapper=self)
else:
_log.debug("Database connection failed, but not due to a known error for dbconn_retry %s",
str(e))
_log.debug("Database connection failed, but not due to a known error for dbconn_retry %s", str(e))
del self._in_connecting
raise
else:
Expand Down
Loading