Using a proxy with Python requests
Copy-ready code for proxies=, sign-in, SOCKS5, sticky sessions, timeouts and retries in a Session.
By DINPROXY Team · · 4 min read
On this page
Python's requests library can send every request through a proxy with one extra argument. This guide gives copy-ready code for DINPROXY residential and mobile proxies: the proxies= dictionary, sign-in, SOCKS5, location and session options, and a Session with timeouts and retries.
Install requests and test your proxy user
Install the library with pip install requests. You also need a proxy user: the full connection username from Tools → Users in the dashboard, such as 1024~myuser, and its password. In every example, replace USERNAME and PASSWORD with them.
Check the proxy user with one cURL command before you write any Python. The reply shows the IP address the site sees, which is the proxy's address rather than your own.
curl --proxy 'http://proxy.dinproxy.com:7777' \ --proxy-user 'USERNAME:PASSWORD' \ 'https://ipinfo.io/ip'Residential proxies use port 7777 and mobile proxies use port 7779, both on proxy.dinproxy.com. The same proxy user works on both, so switching products is a one-number change.
Pass the proxy in the proxies argument
The proxies argument takes a dictionary. Its keys are the schemes of the sites you visit, and its values are the proxy URL. Point both keys at the same http:// proxy URL: it carries HTTP and HTTPS sites alike.
from urllib.parse import quoteimport requests
username = "USERNAME"password = "PASSWORD"proxy = f"http://{quote(username, safe='')}:{quote(password, safe='')}@proxy.dinproxy.com:7777"
response = requests.get( "https://ipinfo.io/ip", proxies={"http": proxy, "https": proxy}, timeout=30,)print(response.text)The sign-in sits inside the proxy URL as USERNAME:PASSWORD@host:port. There, characters such as @ in the username and symbols in the password must be percent-encoded, so wrap both in quote(..., safe=''). Keep this habit from the start, because location and session options also begin with @.
The dashboard can also build these URLs for you. In Rotating Proxies → Connection setup, pick a proxy user, a location and a session type, then choose the User:Pass@IP:Port format: each line is already percent-encoded, so adding http:// in front gives a value you can drop straight into proxies=.
From a server on your IP whitelist, you can leave the sign-in out and write http://proxy.dinproxy.com:7777. To send options from a whitelisted IP, keep the encoded username and leave the password empty: f"http://{quote(username, safe='')}:@proxy.dinproxy.com:7777".
Use SOCKS5 with requests[socks]
The library speaks SOCKS5 through an optional extra. Install it with pip install "requests[socks]", then write the proxy URL with socks5h:// instead of http://. The host, port, username and password stay the same.
# pip install "requests[socks]"from urllib.parse import quoteimport requests
auth = f"{quote('USERNAME', safe='')}:{quote('PASSWORD', safe='')}"proxy = f"socks5h://{auth}@proxy.dinproxy.com:7777"
response = requests.get( "https://ipinfo.io/ip", proxies={"http": proxy, "https": proxy}, timeout=30)print(response.text)With socks5h://, the proxy looks up the site's name, so DNS happens on the proxy side, as it does with http://. For most scripts http:// is all you need; HTTP vs SOCKS5 proxies compares the two in detail.
Choose the location and session in the username
Options go at the end of the username, each written as @name=value. With no options, you get any location and a new IP for every request.
| Option | Example | What it does |
|---|---|---|
country | @country=us | Two-letter country code, lower case |
state | @state=california | State or province, used with country |
city | @city=losangeles | City, used with country |
session | @session=job42 | Letters, digits and _, up to 64 characters. The same ID keeps the same IP |
time | @time=30 | Used with session: how many minutes the IP is kept, 1 to 120 (10 if left out) |
Mobile proxies take country, session and time; state and city targeting is for residential proxies. Location values are lower case with no spaces, such as losangeles. The Select Location list in the dashboard's Connection setup writes them for you.
Rotating is the default: each request gets a new IP. For a sticky session, add an ID and a time, such as USERNAME@country=us@session=job42@time=30. Every request with that ID uses the same IP for up to 30 minutes, and a new ID gives you a new IP. The IP can change sooner if it becomes unavailable or after 60 seconds without requests.
An HTTPS tunnel keeps its IP until it closes, and a requests.Session keeps its connections open for reuse. For a new IP on every HTTPS request, call requests.get() on its own, which opens a fresh connection each time. Use a Session with a session ID when you want one IP for a series of requests. Our post on rotating vs sticky residential proxies covers when each one fits.
Add timeouts and retries
Pass a timeout, in seconds, on every call so that a slow site never holds your script up. The examples in the DINPROXY docs use 30 seconds.
For retries, mount an HTTPAdapter with a urllib3 Retry policy. total caps the number of retries, backoff_factor adds a growing pause between them, and status_forcelist lists the answers to try again. By default, Retry repeats GET and other idempotent methods but not POST; set allowed_methods if a POST is safe to send twice. Retry 502 and 503: the errors page describes both, and in a rotating session each retry goes out through a new IP.
In a sticky session, a retry keeps the session ID and so stays on the same IP. To move on to a new IP, build the proxy URL with a new ID.
Put it together in a Session
A Session reuses connections, shares settings across calls and carries the retry policy. This example keeps one US IP for up to ten minutes and sends two requests through it.
from urllib.parse import quoteimport requests, uuidfrom requests.adapters import HTTPAdapterfrom urllib3.util.retry import Retry
username = f"USERNAME@country=us@session={uuid.uuid4().hex[:12]}@time=10"proxy = f"http://{quote(username, safe='')}:{quote('PASSWORD', safe='')}@proxy.dinproxy.com:7777"retry = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503])
with requests.Session() as s: s.proxies = {"http": proxy, "https": proxy} s.mount("https://", HTTPAdapter(max_retries=retry)) for url in ("https://ipinfo.io/ip", "https://ipinfo.io/json"): print(s.get(url, timeout=30).text) # same IP both timeshttps://ipinfo.io/json shows the IP and location the site sees, so you can confirm the country before a real job. The adapter is mounted for https:// addresses; mount it for http:// as well if you also visit plain HTTP sites.
For mobile IPs, change the port to 7779 and keep the same code. Each account can keep up to 100 connections open at once, residential and mobile together, so size thread pools with that in mind. Each product has its own traffic balance, billed per GB: see Rotating Residential Proxies and Mobile Proxies. For more ways to keep a scraper running smoothly, read how to scrape a website without getting blocked.
Frequently asked questions
Inside a proxy URL, characters such as @ must be percent-encoded, and location and session options start with @. Wrap the username and password in quote(..., safe='').
Install requests[socks] and write the proxy URL with socks5h:// instead of http://. The host, port, username and password stay the same.
Up to 120 minutes, set with @time= next to @session= (10 minutes if you leave time out). The IP can change sooner if it becomes unavailable or after 60 seconds without requests.