Joel Verhagen

a computer programming blog

How to enable an HTTP Proxy in Python

If you are using Python 2's piece-o-crap urllib/urllib2 library mess, here's how to get all the requests to run through an HTTP proxy:

If there is a username an password required:

httpProxy = {'username': 'USERNAME', 'password': 'PASSWORD', 'host': 'HOST', 'port': 'PORT'}
proxyHandler = urllib2.ProxyHandler({'http': 'http://'+httpProxy['username']+':'+httpProxy['password']+'@'+httpProxy['host']+':'+httpProxy['port']})
proxyOpener = urllib2.build_opener(proxyHandler)
urllib2.install_opener(proxyOpener)

If there are no credentials required, try this one out:

httpProxy = {'host': 'HOST', 'port': 'PORT'}
proxyHandler = urllib2.ProxyHandler({'http': 'http://'+httpProxy['host']+':'+httpProxy['port']})
proxyOpener = urllib2.build_opener(proxyHandler)
urllib2.install_opener(proxyOpener)

Now any urllib2 calls made after this will be sent through the proxy.