Django postgresql connect_timeout via environment variable

Recently, I've had to move a postgresql database onto a separate server and split it out from the django application server.

On doing so, we saw intermittent "OperationalError: could not connect to server: Connection timed out".

This was quite obvious that the "connect_timeout" had to be increased to resolve the issue due to the latency introduced by the network. However, psycopg2 database adapter was being used which did not support the "connect_timeout" option to be passed via django.

We were able to work around the issue setting the environmental variable "PGCONNECT_TIMEOUT" so libpq would pick up the connection parameter.

Put the below in "django.wsgi":

os.environ['PGCONNECT_TIMEOUT'] = '30'

Comment