Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 909
csandreas1 Avatar asked Apr 13 '26 21:04

csandreas1


1 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})
like image 87
csandreas1 Avatar answered Apr 15 '26 09:04

csandreas1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!