Working with django : Proxy setup

2019-06-07 06:39发布

问题:

I have a local development django setup with apache. The problem is that on the deployment server there is no proxy while at my workplace I work behind a http proxy, hence the request calls fail.

Is there any way of making all calls from requests library go via proxy. [ I know how to add proxy to individual calls using the proxies parameter but is there a global solution ? ]

回答1:

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"] = {}


回答2:

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"


标签: django proxy