3

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 ? ]

2 Answers 2

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"] = {}
Sign up to request clarification or add additional context in comments.

3 Comments

Proxy servers are always a problem for programmers at IITs !!
what if I want to add authentication details for the proxy (username and password) ??
You need to specify proxies like - http_proxy = "http://username:password@proxy_ip_address_or_domain_name:proxy_port"
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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.