[Django]-Handling database connection errors / operational error exceptions in Python / Django?

3👍

This is a more general solution. However I am not sure how to check which database the error occured. Any comments/ answers wouldd help

from django.db.utils import OperationalError

def db_operational_handler(func):
    def inner_function(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except OperationalError:
            return HttpResponse('Error Establishing a DB connection')
    return inner_function


@db_operational_handler
def Main2(request):
    myqs = customers.objects.all()
    return render(request, 'core/main/main.html', {'qs': myqs})

0👍

Django has support for multiple databases, but this is more designed to allow partitioning of the application over multiple stores, like an authentication database and a content database. See Database routing.

I don’t really see a good way to wrap failover at a single point in Django. I think this is a conscience choice by Django, as there are better suited tools for this at the database level itself, such as pgBouncer. There’s a whole manual section dedicated to this topic. This solution would mean you have 1 connection to a loadbalancer that automatically selects from a pool of available servers.

Leave a comment