0

I want to show instant error page when database host is unavailable. Default behavior for django is that ,when user requests , it takes long time and then displays error page.

Is there is any way to display some error instantly when database host is unreachable or database host is invalid with django without any delay ? Any suggestions ?

Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81

2 Answers2

0

You need to keep checking the socket connection status continuously in a script that will inform you regarding the same. In case you are more concerned with the performance issues then you can make use of a in memory caching system like redis etc.

cheers :-)

Gautam Bhalla
  • 1,170
  • 2
  • 10
  • 16
0

you could do a check for the database during django's init time. a good place to do that would be in a module that is loaded with runserver. for example, your urls.py or a router.py id you have one.

The following snippet is taken from my answer to SO question Testing postgres database accessibility from django

from django.db import connections
conn = connections['default']
try:
    c = conn.cursor() #this will take some time if error
except OperationalError:
    reachable = False
else:
    reachable = True

The code checks if the database is available or not. you could write your logic based on the value of reachable

Community
  • 1
  • 1
srj
  • 9,591
  • 2
  • 23
  • 27
  • the line `c = conn.cursor()` takes long time to execute. And this is not what I am looking for. – Nishant Nawarkhede Dec 01 '14 at 11:39
  • @Fledgling, This is a one-time logic that is performed when django boots up. You could have instant error based on the value of `reachable` (put it in a shared location). The downside is that if your database fails any time after that, there is no way of finding that out. you are better off with some monitoring tools like Nagios for continuos monitoring. – srj Dec 02 '14 at 06:57