[Fixed]-How to set timeout for database connection in django

31👍

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,
        }
    }
}

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

Leave a comment