18

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?

2 Answers 2

34

ONLY FOR DJANGO ≥ 1.2

You can use the OPTIONS dictionary of your DATABASES setting.

The option name depends on your DB backend, but for PostgreSQL it would be connect_timeout:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        …
        'OPTIONS': {
            'connect_timeout': 5,
        }
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

DATABASE_OPTIONS seems to be changed to OPTIONS since Django 1.2 (docs.djangoproject.com/en/1.9/releases/1.2)
'connect_timeout' also seems outdated, at least for Django1.9. Just 'timeout' is accepted, I hope it is the correct replacement.
@zeycus connect_timeout is the correct option for Postgres. psycopg2 2.7.3.2 errors with "invalid connection option" if timeout is used. The Django docs only mention timeout for Sqlite users.
For mysql 5.7 default value for connect_timeout is 10 dev.mysql.com/doc/refman/5.7/en/…
Thanks. This really helps. How do I get supported OPTIONS? Is there any way we can find?
|
5

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;-).

2 Comments

Is this a generic setting that work with all django-supported database backends? (I googled and only found it mentioned in relation to SQLAlchemy)
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).

Your Answer

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