https://github.com/sectorlabs/django-db-connection-retrier
Automatically re-establish Django's database connection when it fails due to DNS errors.
https://github.com/sectorlabs/django-db-connection-retrier
Last synced: about 1 year ago
JSON representation
Automatically re-establish Django's database connection when it fails due to DNS errors.
- Host: GitHub
- URL: https://github.com/sectorlabs/django-db-connection-retrier
- Owner: SectorLabs
- License: mit
- Created: 2019-09-16T19:20:47.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2024-03-20T15:46:30.000Z (about 2 years ago)
- Last Synced: 2025-03-27T15:56:02.765Z (about 1 year ago)
- Language: Python
- Size: 14.6 KB
- Stars: 4
- Watchers: 18
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Django Database Connection Retrier
[](http://doge.mit-license.org)
[](https://pypi.python.org/pypi/django-db-connection-retrier)
[](https://circleci.com/gh/SectorLabs/django-db-connection-retrier/tree/master)
Automatically try to re-establish Django database connections when they fail due to DNS errors.
---
When the Django app (`dbconnectionretrier`) loads, a hook is installed in Django's [`BaseDatabaseWrapper.ensure_connection`](https://github.com/django/django/blob/master/django/db/backends/base/base.py#L216) that catches `django.db.OperationalError`. If the error raised is a DNS error, the connction attempt is retried synchronously **three times**.
---
Tested on Django 2.0-2.3 and Python 3.7 and 3.8. Might work with other versions of Django and Python.
## Installation
1. Install the package from PyPi:
$ pip install django-db-connection-retrier
2. Add `dbconnectionretrier` to your `INSTALLED_APPS`:
INSTALLED_APPS = [
'dbconnectionretrier',
...
]
## Manual usage
Adding `dbconnectionretrier` to `INSTALLED_APPS` enables automatic connection retrying. Want more granular control over patching?
### Globally
```
from dbconnectionretrier.patch import patch_ensure_connection
# after this line executes, connection retrying is enabled
patch = patch_ensure_connection()
# after this line, the connection retrying is disabled
patch.rollback()
```
### Context manager
```
from dbconnectionretrier.patch import patch_ensure_connection_contextual
with patch_ensure_connection_contextual():
# all code inside this block benefits from connection retrying
```