tags:

views:

263

answers:

3

I have mysql database as engine for django. Django works thought nginx via fastcgi with timeout in 1 min (after that nginx says "504 gateway time-out").

If database gone down, django is trying reconnect to DB and waiting for response from it. And waiting for response too long (more than 1 minute) that nginx returns to client the 504 error code.

How to set timeout for db connecton in django? And what the right way to handle this event and return to client a pretty page with "Sorry database is out of service now. Please try later" instead of technical 504 error page?

A: 

DATABASE_OPTIONS in settings.py is a dict of extra keyword args that are passed to the connect method of whatever database module is in use; per MySqlDB's docs on connect, the connect_timeout value, as the other answer says, is indeed what you want there (I had it wrong before, and it varies by backend -- for example, it's spelled timeout if your backend is SQLite).

For custom error pages, you can follow the advice in the Django docs about writing your own exception middleware (I'm sure simple exception middleware that just shows a customized page can be found in contributed software, but it may be faster to roll your own than to search the web for existing code, and you'd probably have to tweak that code anyway;-).

Alex Martelli
Is this a generic setting that work with all django-supported database backends? (I googled and only found it mentioned in relation to SQLAlchemy)
lemonad
no it wasn't, my bad -- fixed now -- note that there is no single way that works with all DBs, but connect_timeout works with MySql, timeout works with SQLite, etc (always as keys in DATABASE_OPTIONS in settings.py).
Alex Martelli
+2  A: 

I think you can use the DATABASE_OPTIONS setting:

DATABASE_OPTIONS = {
    "connect_timeout": 60,
}
lemonad
A: 

I have tried this solution in my settings.py and it does not seem to work. I am using MySql just so u know. Any other help would be appreciated.

en