The basics: the proxies dictionary
requests chooses a proxy by the scheme of the URL you request. Set both the http and https keys, usually to the same proxy, or HTTPS requests will bypass it. The proxy URL itself carries the scheme, credentials, host and port.
import requests
PROXY = "http://USERNAME:PASSWORD@PROXY_HOST:PORT"
proxies = {"http": PROXY, "https": PROXY}
r = requests.get("https://api.ipify.org", proxies=proxies, timeout=15)
print(r.text) # the proxy's IPSOCKS5 with remote DNS
Install the SOCKS extra, then use the socks5h scheme. The h means the hostname is resolved by the proxy. With plain socks5, your machine resolves the name first: DNS leaves from your own network and regional sites may answer for the wrong country.
| Scheme | Protocol to the proxy | DNS resolved by |
|---|---|---|
| http:// | HTTP (CONNECT for HTTPS sites) | The proxy |
| socks5:// | SOCKS5 | Your machine |
| socks5h:// | SOCKS5 | The proxy (recommended) |
# pip install "requests[socks]"
import requests
PROXY = "socks5h://USERNAME:PASSWORD@PROXY_HOST:PORT"
r = requests.get("https://api.ipify.org",
proxies={"http": PROXY, "https": PROXY}, timeout=15)
print(r.text)Sessions, timeouts and retries
Reuse a Session so connections are pooled, always pass a timeout so a stuck request cannot hang your program, and retry only a few times with backoff. urllib3's Retry handles backoff for you.
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
PROXY = "socks5h://USERNAME:PASSWORD@PROXY_HOST:PORT"
session = requests.Session()
session.proxies = {"http": PROXY, "https": PROXY}
retry = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
session.mount("http://", HTTPAdapter(max_retries=retry))
session.mount("https://", HTTPAdapter(max_retries=retry))
r = session.get("https://example.com/", timeout=(10, 30)) # connect, readexport HTTPS_PROXY="http://USERNAME:PASSWORD@PROXY_HOST:PORT"
export HTTP_PROXY="$HTTPS_PROXY"
python my_script.py # requests reads these automaticallyCommon mistakes
Most proxy problems in requests come from a handful of mistakes. Check these before anything else.
- Only the http key is set, so HTTPS requests go direct.
- socks5 instead of socks5h, so DNS is resolved locally.
- Special characters in the password are not URL-encoded (use urllib.parse.quote).
- No timeout, so one stalled connection blocks the whole job.
- Unbounded retries that multiply traffic when a site is refusing requests.
Async requests: httpx and aiohttp
For many requests at once, an async client beats threads around requests. httpx takes the proxy in the client and supports SOCKS5 with the socks extra. aiohttp takes an HTTP proxy per request and needs aiohttp-socks for SOCKS5; rdns=True resolves hostnames through the proxy.
# pip install "httpx[socks]"
import asyncio, httpx
PROXY = "socks5://USERNAME:PASSWORD@PROXY_HOST:PORT"
async def main():
async with httpx.AsyncClient(proxy=PROXY, timeout=30) as client:
r = await client.get("https://api.ipify.org")
print(r.text)
asyncio.run(main())# pip install aiohttp aiohttp-socks
import asyncio, aiohttp
from aiohttp_socks import ProxyConnector
async def main():
# HTTP proxy: pass it per request
async with aiohttp.ClientSession() as s:
async with s.get("https://api.ipify.org", proxy="http://USERNAME:PASSWORD@PROXY_HOST:PORT") as r:
print(await r.text())
# SOCKS5: needs a connector
conn = ProxyConnector.from_url("socks5://USERNAME:PASSWORD@PROXY_HOST:PORT", rdns=True)
async with aiohttp.ClientSession(connector=conn) as s:
async with s.get("https://api.ipify.org") as r:
print(await r.text())
asyncio.run(main())Rotate proxies and handle errors
Spread requests over several proxies and retry a failed one on another. Catch the proxy errors separately from the target's errors: a ProxyError means the proxy didn't connect, while a 403 or 429 from the site means the request went through and the site refused it.
| Error | Cause | Fix |
|---|---|---|
| ProxyError | Can't connect to or through the proxy | Check host, port and that the proxy is active; retry on another |
| 407 Proxy Authentication Required | Wrong or missing proxy login | Check the credentials; URL-encode special characters in the password |
| ConnectTimeout / ReadTimeout | Slow exit or target | Raise the timeout or retry on another proxy |
| SSLError through the proxy | Something intercepts TLS, or an old certificate store | Update certifi; don't turn verification off in production |
| 403 or 429 from the site | The site refused or rate-limited the request | Slow down, rotate IPs, send realistic headers |
import random, requests
from urllib.parse import quote
PROXIES = [
"http://USERNAME:PASSWORD@PROXY_HOST_1:PORT",
"http://USERNAME:PASSWORD@PROXY_HOST_2:PORT",
]
def get(url):
for attempt in range(3):
proxy = random.choice(PROXIES)
try:
return requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=20)
except requests.exceptions.ProxyError:
continue # try another proxy
raise RuntimeError("all proxies failed")
# A password with @, : or / must be URL-encoded first:
password = quote("p@ss:word", safe="")Proxy authentication, session proxies and skipping the proxy
requests reads the proxy login from the proxy URL: http://USERNAME:PASSWORD@PROXY_HOST:PORT. That works for HTTP and HTTPS sites alike. requests.auth.HTTPProxyAuth only adds a Proxy-Authorization header to plain HTTP requests, so it doesn't help with HTTPS, where the login has to go out with the CONNECT request. Keep the credentials in the URL, built from environment variables rather than written into code you commit.
A proxy set on session.proxies can lose to HTTP_PROXY and HTTPS_PROXY from the environment, because requests merges environment settings into each request. If a script ignores the proxy you set on the session, set session.trust_env = False or pass proxies= on every request.
To skip the proxy for some hosts, list them in NO_PROXY. To skip it for a whole session, use trust_env = False and set no proxies.
import os, requests
from urllib.parse import quote
user = os.environ["PROXY_USER"]
password = quote(os.environ["PROXY_PASS"], safe="")
PROXY = f"http://{user}:{password}@PROXY_HOST:PORT"
session = requests.Session()
session.trust_env = False # ignore HTTP(S)_PROXY from the environment
session.proxies = {"http": PROXY, "https": PROXY}
print(session.get("https://api.ipify.org", timeout=15).text) # proxy IP
# No proxy at all for this session:
direct = requests.Session()
direct.trust_env = False
print(direct.get("https://api.ipify.org", timeout=15).text) # your own IPexport HTTPS_PROXY="http://USERNAME:PASSWORD@PROXY_HOST:PORT"
export NO_PROXY="localhost,127.0.0.1,.internal.example.com"
python my_script.py # these hosts skip the proxy