django

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'

Django HTTPS Redirects

This works for both HTTP and HTTPS where any front end web server such as nginx which handles the actual request sets a header when request comes via HTTPS. In Apache configuration you then use mod_setenvif to set the HTTPS variable, which Django then picks up to use for redirection.

With front end nginx server which handles SSL, set header "X-Forwarded-Proto=https" via:

  proxy_set_header X-Forwarded-Proto https;

On Apache, add directive:

  SetEnvIf X-Forwarded-Proto https HTTPS=1

The HTTPS variable is picked up as being special by mod_wsgi and it will fix the wsgi.url_scheme in WSGI environment which Django then uses for redirection.

This way you don't need to customize Django stack.

Comment