Skip to content

Instantly share code, notes, and snippets.

@sid24ss
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save sid24ss/df910c5b6904c1f84f48 to your computer and use it in GitHub Desktop.

Select an option

Save sid24ss/df910c5b6904c1f84f48 to your computer and use it in GitHub Desktop.
Deploying Django with mod_wsgi on a server behind proxy

Follow the steps for deploying Django with Apache and mod_wsgi.

This means that the WSGIDaemon runs under the user www-data, which is a special linux user for Apache.

If you have to connect to the internet, you need to set the $http_proxy and $https_proxy variables. Set them in your /etc/environment file.

This still doesn't mean that the environment variables are set for the www-data user. You need to set the same in the /etc/apache2/envvars file, which sets the environment variables for the www-data user.

# /etc/apache2/envvars
export http_proxy=http://127.0.0.1:3128/
export https_proxy=https://127.0.0.1:3128/

(as a side note, I'm using CNTLM - which is why the 127.0.0.1:3128 proxy settings)

In the django code, in your settings.py, do something like:

# settings.py
PROXIES = {
    'http' : os.environ.get('http_proxy'),
    'https' : os.environ.get('https_proxy'),
    'ftp' : os.environ.get('ftp_proxy'),
    'socks' : os.environ.get('socks_proxy'),
}

# when you want to get a resource from the internet
# using urllib2
opener =  urllib2.build_opener(urllib2.ProxyHandler(settings.PROXIES))
urllib2.install_opener(opener)
url = 'https://maps.googleapis.com/maps/api/geocode/json?'
res = urllib2.urlopen(url).read()

# using requests
response = requests.get('https://maps.googleapis.com/maps/api/geocode/json', proxies=settings.PROXIES)

The same code works when you run the management server using manage.py runserver, if you have the proxy settings in your environment variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment