Two ways to rotate proxies in Python. With a rotating gateway, the provider changes the IP: leave the session out for a new IP with each request, or add a session ID to keep one IP for a while (a sticky session).
With your own proxy list, your code picks the next proxy: round robin, random, or a pool that benches a proxy after it fails. Both plug into the same retry helper, which sends a failed request again through a new IP after a short backoff. The examples use Requests for sync code and aiohttp for concurrent requests, on Python 3.10 or newer.
This repo goes with the guide How to Rotate Proxies in Python.
git clone https://github.com/IPRoyal/rotate-proxies-python.git
cd rotate-proxies-python
pip install -r requirements.txt
cp .env.example .env # then add your proxy username and password
python examples/rotating_vs_sticky.pyThe script sends five requests without a session and five on one sticky session, then prints the exit IP of each, as icanhazip sees it:
Request Rotating (no session) Sticky (session Xy7Kp2Qa, 10m)
1 <IP 1> <IP A>
2 <IP 2> <IP A>
...
The gateway examples use IPRoyal residential proxies. One endpoint, geo.iproyal.com, handles both rotation modes, set in the password string (IPRoyal docs):
- Rotating: no session, so a new IP with each request (the default)
- Sticky:
_session-plus 8 letters or digits keeps one IP, and_lifetime-sets for how long, from 1 second to 7 days (10m,2h,1d) - Targeting:
_country-,_state-(US) or_city-, combined with either mode
proxy_config.py builds that string, and rotation.py wraps it in two proxy sources:
from rotation import gateway_rotating_from_env, sticky_session_from_env
rotating = gateway_rotating_from_env()
rotating.get()
# http://username:password@geo.iproyal.com:12321
sticky = sticky_session_from_env(lifetime="10m")
sticky.get()
# http://username:password_session-Xy7Kp2Qa_lifetime-10m@geo.iproyal.com:12321
sticky.rotate() # a new session ID, so a new IPUse rotating requests when every request stands alone, and a sticky session when a site ties cookies or a login to the IP.
Proxies from any provider work, one per line in proxies.txt (copy proxies.example.txt). A line can be a full URL (http://user:pass@host:port), host:port:user:pass or host:port.
from rotation import ProxyPool, RandomRotator, RoundRobin, load_proxy_list
proxies = load_proxy_list("proxies.txt")
RoundRobin(proxies) # each proxy in turn
RandomRotator(proxies) # a random proxy each time, like random.choice in the guide
ProxyPool(proxies, max_failures=3, cooldown=300)ProxyPool counts failures in a row for each proxy. At max_failures the proxy sits out for cooldown seconds, then rejoins with a clean record, and a success resets the count. If every proxy is benched, get() raises NoProxyAvailable and says when the first one is back.
python examples/proxy_list_rotation.pyThe script sends six requests with each strategy and prints which proxy each one used. IPRoyal datacenter proxies are bought per IP, each with its own port and credentials in the dashboard's proxy list (IPRoyal docs), so this is how you rotate across them.
from retry import fetch_with_retry
response = fetch_with_retry("https://example.com/", source, attempts=4)source is any of the five sources above. When a request fails, the helper tells the source, waits, and tries again:
| Source | What a failure does |
|---|---|
| Rotating gateway | Nothing: the next request gets a new IP anyway |
| Sticky session | Switches to a new session ID, so a new IP |
| Round robin, random | Nothing: the next request takes the next proxy |
| Proxy pool | Counts the failure and benches the proxy at max_failures |
What gets a retry: connection errors, timeouts, and 429, 500, 502, 503 or 504 answers. Every other status comes back to you. A 407 raises ProxyAuthError at once, because a new IP won't fix a wrong username or password.
The wait doubles with each attempt (about 1, 2, 4 seconds, up to 30), with some randomness so parallel workers don't retry in step. A 429 with a Retry-After header in seconds waits at least that long. Check the target site's terms before you send it automated traffic.
python examples/retry_on_failure.py https://example.com/For anything else that takes a proxy URL, with_retry(call, source) runs call(proxy_url) and retries when it raises RetryableError.
aiohttp takes the proxy on each request, so every concurrent request can come from the same source:
import asyncio
from async_rotation import fetch_all
results = asyncio.run(fetch_all(urls, source, concurrency=5))fetch_all returns one item per URL: the body, or the exception if every attempt failed. A sticky session that fails switches to a new ID once, even when several requests on it fail together.
aiohttp keeps connections open for reuse by default, and requests sent through one open HTTPS tunnel share its exit IP. So fetch_all closes each connection after its request. Pass reuse_connections=True for a sticky session, where one IP is the point.
python examples/async_rotation.pyThe async example takes HTTP proxies (IPROYAL_SCHEME=http).
A flow such as sign in, then browse, then check out needs one IP for every step, often from one country:
from retry import with_retry
from rotation import sticky_session_from_env
from sticky_country_session import run_flow
sticky = sticky_session_from_env(lifetime="30m", country="us")
result = with_retry(run_flow, sticky, attempts=3)run_flow makes three requests on one sticky session with _country-us and checks they all left from the same IP. If a step fails or the IP changes, the whole flow starts over on a new session ID with a fresh cookie jar, so a finished flow ran on one IP from start to end.
python examples/sticky_country_session.py # US
python examples/sticky_country_session.py de # GermanyThe list examples (proxy_list_rotation.py and the pool in async_rotation.py) take proxies from any provider: put them in proxies.txt or point PROXY_LIST in .env at another file.
The gateway examples always use the IPROYAL_* settings, because sessions and targeting are IPRoyal password options. To use another rotating gateway, wrap its URL in GatewayRotating(url). For its sticky sessions, pass StickySession a function that turns a session ID into that provider's proxy URL.
The sync examples work over SOCKS5 too: set IPROYAL_SCHEME=socks5 or use socks5:// URLs in the list, and pip install "requests[socks]".
pip install -r requirements-dev.txt
pytestThe offline tests need no proxy account and no network. They cover:
- proxy strings: session IDs, lifetimes, targeting and list-file parsing
- rotation: round robin order, random picks with a seeded generator, benching and the cooldown on a fake clock
- retries: a new session for each attempt, backoff limits,
Retry-After, no retry on 407 - client wiring: Requests and aiohttp through a local mock proxy that asks for credentials, echoes what it got and fails on cue, plus a dead local port to bench
They run on every push (test.yml).
The live check sends about 25 small requests through IPRoyal. It checks that rotating requests return more than one IP, that a sticky session keeps one IP and a new session ID changes it, that country-us exits in the US, and that a wrong password raises ProxyAuthError:
python scripts/live_check.pyOn GitHub it runs by hand from the Actions tab (live-check.yml) with the IPROYAL_USERNAME and IPROYAL_PASSWORD secrets.
proxy_config.py builds the IPRoyal proxy URL from .env
rotation.py proxy sources: gateway (rotating, sticky) and your own list (round robin, random, pool)
retry.py retry with a new proxy and backoff, for Requests and aiohttp
examples/ one script per topic
proxies.example.txt proxy list format
scripts/live_check.py live run through IPRoyal
tests/ offline tests with a local mock proxy
The guide explains why rotation matters and compares a proxy list with a rotating gateway: How to Rotate Proxies in Python.
