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

Question:

I am running multiple databases and I need to handle this exception. How can I do it either in the view or a more general approach ? I am using PostgreSQL. It’s a bit ugly to wrap my whole code like below.

import psycopg2
def Main(request):
    try:
        myqs = customers.objects.all()
    except psycopg2.OperationalError as e:
        print('operational error, handle this')

    return render(request, 'core/main/main.html', {'qs': myqs})

enter image description here

Asked By: csandreas1

||

Answers:

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})
Answered By: csandreas1

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.

Answered By: user1600649
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.