3

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

0

2 Answers 2

4

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})
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.