[Django]-Working with django : Proxy setup

5๐Ÿ‘

โœ…

Add following lines in your wsgi file.

import os

http_proxy  = "10.10.1.10:3128"
https_proxy = "10.10.1.11:1080"
ftp_proxy   = "10.10.1.10:3128"

proxyDict = { 
              "http"  : http_proxy, 
              "https" : https_proxy, 
              "ftp"   : ftp_proxy
            }

os.environ["PROXIES"] = proxyDict

And Now you can use this environment variable anywhere you want,

r = requests.get(url, headers=headers, proxies=os.environ.get("PROXIES"))

P.S. โ€“ You should have a look at following links

  1. Official Python Documentation for Environment Variables
  2. Where and how do I set an environmental variable using mod-wsgi and django?
  3. Python ENVIRONMENT variables

UPDATE 1

You can do something like following so that proxy settings are only being used on localhost.

import socket
if socket.gethostname() == "localhost":
    # do something only on local server, e.g. setting os.environ["PROXIES"]
    os.environ["PROXIES"] = proxyDict
else:
    # Set os.environ["PROXIES"] to an empty dictionary on other hosts
    os.environ["PROXIES"] = {}
๐Ÿ‘คpankaj28843

5๐Ÿ‘

I got the same error reported by AmrFouad. At last, it fixed by updating wsgi.py as follows:

os.environ['http_proxy'] = "http://proxy.xxx:8080"
os.environ['https_proxy'] = "http://proxy.xxx:8080"
๐Ÿ‘คTommy Tang

Leave a comment