Proxy setup in Python requests

Proxies in Python requests: the proxies dict, SOCKS5 via socks5h, a new IP per request (823) or one IP per session, and a check via api.ipify.org.

Updated · Prokso editorial team

Markdown, ready to paste into ChatGPT or another AI assistant
Connection details
Host
gw.prokso.com
Port
823 HTTP · 824 SOCKS5 - new IP per request · 10000–20000 sticky session, HTTP(S) and SOCKS5
Username and password
in your dashboard, on the plan page

Your dashboard generates ready-made lines in the format you need: choose the country, IP type and protocol.

Key takeaways
  • Host gw.prokso.com, ports 823 (HTTP), 824 (SOCKS5), 10000–20000 (sticky sessions, HTTP or SOCKS5)
  • The username and password are in your dashboard on the plan page
  • Check the IP in the response of the proxied request itself: the My IP page in a browser does not test your script
Proxies in Python requests: a short video guide · 0:38 · Open the video page
Video transcript

Prokso proxies in Python requests.

First, get your proxy details from the dashboard: host, port, username and password. They are on the plan page, in the Access block.

In Python, pass the proxy address to the proxies parameter of the requests library - the same for http and https. And always set a timeout.

Run the example: the output should show the proxy IP, not yours. On port 823, every run gets a new address.

The full guide with examples is on the Prokso website.

A step-by-step guide to connecting Prokso proxies in Python requests. It takes a few minutes.

Step 1. Get the proxy details from your dashboard

Open your plan and copy the host gw.prokso.com, port, username and password. Port 823 is HTTP and 824 is SOCKS5 (both give a new IP for every request); ports 10000–20000 keep one IP (sticky session) for up to 120 minutes and work as both HTTP and SOCKS5 (each port is a separate address). Set the country in the username: username__cr.ua.

The “Access” block on the plan page: host, ports, username and password for the proxy line
The “Access” block on the plan page: host, ports, username and password for the proxy line

Step 2. Install the library

You need Python 3 and the requests library: pip install requests. For SOCKS5: pip install "requests[socks]".

Step 3. Pass the proxy to the request

Put the proxy in the proxies dict for http and https. The code below prints the IP the website sees.

import requests

proxy = "http://USERNAME:PASSWORD@gw.prokso.com:823"
proxies = {"http": proxy, "https": proxy}

r = requests.get("https://api.ipify.org?format=json", proxies=proxies, timeout=30)
print(r.json())

Step 4. SOCKS5 and a sticky session

For SOCKS5 change the scheme to socks5h:// and the port to 824. To send several requests from one IP, use a port from 10000–20000 instead of 823 or 824 - it works with both http:// and socks5h://.

# pip install "requests[socks]"
proxy = "socks5h://USERNAME:PASSWORD@gw.prokso.com:824"   # socks5h - DNS through the proxy too

Step 5. Check the script output

Run the code from step 3: it requests https://api.ipify.org through the proxy and prints {"ip": "…"} - the address the website sees. It should differ from yours. Run it twice: on 823 the IP changes, on a sticky port it stays the same. The My IP page in your browser won't help here, as the browser doesn't use this proxy.

Example run: the output shows the proxy IP, not yours. On port 823 every run gets a new address
Example run: the output shows the proxy IP, not yours. On port 823 every run gets a new address

Session, timeouts, and retries

For a series of requests, create a requests.Session() and set the proxy once: a session reuses connections and runs noticeably faster. Always set a timeout: without one, a hung request will stop your script forever. Through residential and mobile addresses a response takes longer than it does directly, so 30 seconds is a reasonable starting point.

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

proxy = "http://USERNAME:PASSWORD@gw.prokso.com:823"

s = requests.Session()
s.proxies = {"http": proxy, "https": proxy}
# retry only temporary failures, with a growing pause
retry = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
s.mount("http://", HTTPAdapter(max_retries=retry))
s.mount("https://", HTTPAdapter(max_retries=retry))

r = s.get("https://prokso.com/ip", timeout=30)
print(r.status_code, r.text)

Only temporary failures are worth retrying: 502, 503, 504, and timeouts. On port 823 every retry goes out from a new IP. Codes 403 and 429 come from the site: an immediate retry will not fix them and will only spend traffic.

Environment variables: HTTP_PROXY, HTTPS_PROXY, NO_PROXY and trust_env

requests takes proxies not only from the proxies argument. If you don't pass it, the library reads the environment variables http_proxy, https_proxy, all_proxy and no_proxy (uppercase works too), as the requests documentation says. This is handy when you'd rather not edit the script: the proxy is set before the run.

export HTTP_PROXY="http://USERNAME:PASSWORD@gw.prokso.com:823"
export HTTPS_PROXY="http://USERNAME:PASSWORD@gw.prokso.com:823"
export NO_PROXY="localhost,127.0.0.1"   # addresses that go direct
python script.py

Write http:// in HTTPS_PROXY too, just like in the proxies dict. NO_PROXY is a comma-separated list of addresses that go direct. The requests documentation warns that a password in an environment variable or in a file under git is a security risk: don't keep it where others can see it.

The main trap is s.proxies on a session. According to the requests documentation, proxies from environment variables override session.proxies. We checked this on requests 2.34: with HTTP_PROXY set in the system, a session with its own s.proxies went through the proxy from the variable. So either pass proxies= to every request or turn off reading the environment with trust_env = False:

import requests

proxy = "http://USERNAME:PASSWORD@gw.prokso.com:823"

s = requests.Session()
s.trust_env = False  # don't read proxies from environment variables
s.proxies = {"http": proxy, "https": proxy}
print(s.get("https://api.ipify.org", timeout=30).text)

How to disable the proxy for a single request

Sometimes a proxy is set for the whole program, but one request, say to your own API, has to go direct. Pass None for both schemes to it. According to the requests documentation, a key set to None is dropped from the parameters, and proxies from environment variables are no longer filled in for that request.

import requests

# HTTP_PROXY and HTTPS_PROXY are set in the system: this request goes through the proxy
r = requests.get("https://api.ipify.org", timeout=30)

# and this one goes direct, from your own IP
direct = requests.get("https://api.ipify.org", proxies={"http": None, "https": None}, timeout=30)

We checked this on requests 2.34.2 with a local test proxy: a request with proxies={"http": None, "https": None}, a session with trust_env = False and an address listed in NO_PROXY all go direct. A plain request without these settings goes through the proxy from the variable. If you have many direct requests, keep a separate session for them with trust_env = False and no proxies.

What the errors mean

ErrorWhat it meansWhat to do
ProxyError with code 407The proxy did not accept the username or password.Check the string and the remaining traffic on your plan.
ConnectTimeoutThe script could not reach the proxy.Check the host and port, and whether the port is blocked on your network.
ReadTimeoutThe proxy is reachable, but the site did not respond in time.Increase the timeout or retry the request.
Missing dependencies for SOCKS supportThe package for SOCKS is not installed.Run pip install "requests[socks]".
No error, but the IP isn't the one from s.proxiesHTTP_PROXY or HTTPS_PROXY is set in the system, and requests took the proxy from there.Pass proxies= to the request or set s.trust_env = False, see the section on environment variables.

The response codes are explained on the proxy error codes page.

How to spend less traffic

Traffic is counted by the size of the responses. Request data through the site's API if it has one: JSON is several times lighter than an HTML page. Do not download again what you already have, and do not load images if you only need the text. The traffic calculator will help you estimate the volume in advance.

ThreadPoolExecutor: one Session and one IP per worker

requests doesn't promise that one Session is safe to share between threads. Create a session per thread with threading.local() and give each worker its own session number in the username: one worker keeps its IP for about 30 minutes, while different workers go out from different addresses.

import os
import threading
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import quote

import requests

USER = "USERNAME"
PASSWORD = os.environ["PROKSO_PASSWORD"]  # export PROKSO_PASSWORD=... before the run
local = threading.local()


def session_for_worker():
    if not hasattr(local, "s"):
        worker = threading.current_thread().name.split("_")[-1]
        login = f"{USER}__cr.us;sessid.w{worker}"  # own IP per worker for about 30 minutes
        proxy = f"http://{quote(login, safe='')}:{quote(PASSWORD, safe='')}@gw.prokso.com:823"
        s = requests.Session()
        s.trust_env = False  # ignore HTTP_PROXY from the system
        s.proxies = {"http": proxy, "https": proxy}
        local.s = s
    return local.s


def fetch(url):
    r = session_for_worker().get(url, timeout=30)
    return url, r.status_code, len(r.content)


urls = [f"https://example.com/item/{n}" for n in range(1, 41)]
with ThreadPoolExecutor(max_workers=4, thread_name_prefix="w") as pool:
    for url, code, size in pool.map(fetch, urls):
        print(code, size, url)

The password comes from an environment variable, and quote(..., safe="") encodes it and the ; in the username. trust_env = False makes sure a system HTTP_PROXY doesn't replace your address. max_workers is how many requests run at once: for one website keep it small.

Silent leaks and parse errors in requests

These errors either don't look like errors at all or are easy to blame on the proxy:

  • Only the "http" key in proxies. Requests to https:// sites then go direct, with no error, from your own IP. Always set both keys and check the IP with https://api.ipify.org through the same session.
  • SSLError right when connecting to the proxy. The proxy URL starts with https://, so requests tries to open TLS to the proxy itself. Write http:// in the proxy URL even for https sites: the connection to the website is still encrypted end to end inside the tunnel.
  • InvalidProxyURL: Please check proxy URL. It is malformed and could be missing the host. An unencoded @ or / in the password broke the URL. Build it with quote() as in the example.
  • ProxyError with "Tunnel connection failed" and a code other than 407. The proxy refused to open a tunnel to the website: it's on the blocked sites list or uses a closed port (mail ports are closed).
  • 429 and 403. These come from the website. For 429 look at the Retry-After header and pause that worker; for 403 slow down and check the website's rules.

Rotation, sessid and pace for a requests scraper

Port 823 without a session number gives every request a new IP: good for independent pages such as product cards. A session number per worker suits pagination and anything with cookies. For jobs longer than 30 minutes take a sticky port from 10000-20000 per worker and set the hold time in the dashboard.

requests asks for compressed responses by default (the Accept-Encoding header with gzip and deflate), so don't replace it with identity: the website will send more bytes, and traffic is counted in both directions. The result line of the example prints the size of each response, which helps to see which pages are the heaviest.

If the proxy does not work

FAQ

How do I run many threads?

Use concurrent.futures or asyncio with aiohttp. Every thread can use the same port 823 - each gets a different IP.

Why does requests go through a proxy when I did not set one?

The library reads the HTTP_PROXY and HTTPS_PROXY environment variables. To turn this off, set trust_env = False on the session.

How do I encode special characters in the password?

Pass the username and password through urllib.parse.quote(..., safe="") before you build the proxy address. Otherwise the @ and : characters will break the parsing of the address.

How do I set the country in code?

The country is written in the username, for example USERNAME__cr.de. Change the username: the address and port stay the same.

Can I share one Session between threads?

Better not. requests doesn't guarantee thread safety for a session, and with one session all threads also share cookies. Create a session per thread as in the example.

Why did a worker's IP change before 30 minutes passed?

A residential or mobile address belongs to a real device, and if it leaves the network the session gets a new IP in the same country. Write the code so a worker can repeat the last step, for example sign in again.

Is the connection to an https site encrypted through an http:// proxy?

Yes. requests opens a tunnel through the proxy with the CONNECT method, and TLS runs between your script and the website. The proxy sees the domain name, but not the content of pages or passwords.

How do I disable the proxy for just one request in requests?

Pass that request a proxies argument with None for both the http and https keys. Other requests still go through the proxy from the environment variables or the session settings.

Why doesn't s.proxies on my session take effect?

If HTTP_PROXY or HTTPS_PROXY is set in the system, requests uses them instead of session.proxies. Pass proxies= to every request or set s.trust_env = False.

Was this guide helpful?

Proxy not working? Check it in 6 steps

Install the Prokso app