aiohttp Proxy: HTTP, HTTPS and SOCKS5

Proxies in aiohttp for Python: the proxy parameter on a request, credentials in the URL, SOCKS5 with aiohttp-socks and choosing a port for parallel requests.

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
  • Generator format - protocol://username:password@host:port with the http:// scheme, the line goes into proxy= unchanged
  • SOCKS5 - only through aiohttp-socks and ProxyConnector, port 824 or a sticky port
  • The correct result - a dictionary with the ip key and the proxy address in the script output
Proxies in aiohttp: a short video guide · 0:38 · Open the video page
Video transcript

Prokso proxies in aiohttp.

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

In aiohttp, pass the proxy address with the proxy parameter right in the request. Create one session for the whole script.

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 aiohttp. It takes a few minutes.

Step 1. Prepare the proxy URL for the proxy= parameter in aiohttp

aiohttp takes the proxy as a URL in the proxy parameter of a request or session, with the username and password inside the address. So in the dashboard generator choose the protocol://username:password@host:port format and the HTTP(S) protocol: you get the line http://USERNAME:PASSWORD@gw.prokso.com:823, which goes into the code as is.

The http:// scheme is correct here for https sites too. According to the aiohttp documentation, the library works with plain HTTP proxies and those that open a tunnel with the CONNECT method, while support for proxies with an https:// address is limited. SOCKS5 needs a separate package, aiohttp-socks: then choose the SOCKS5 protocol in the generator, and the line will start with socks5://.

The port depends on how you collect data. Port 823 gives a new IP for every request, which is handy for parallel collection. Sticky ports 10000-20000 keep one address for 1 to 120 minutes; you need them when several requests must come from one visitor. The country is set by the suffix in the username (username__cr.ua - Ukraine), so for another country only the part of the URL before the password changes.

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

pip install aiohttp. For SOCKS5 you also need pip install aiohttp-socks.

Step 3. Pass the proxy to the request

aiohttp accepts an HTTP proxy in the proxy parameter of each request. Put the username and password straight into the URL.

import asyncio
import aiohttp

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


async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://api.ipify.org?format=json", proxy=PROXY) as r:
            print(await r.json())


asyncio.run(main())
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

Step 4. SOCKS5 with aiohttp-socks

aiohttp itself does not support SOCKS. Create a ProxyConnector from the aiohttp-socks package and pass it to the session - then every request in the session goes through SOCKS5.

import asyncio
import aiohttp
from aiohttp_socks import ProxyConnector


async def main():
    connector = ProxyConnector.from_url("socks5://USERNAME:PASSWORD@gw.prokso.com:824")
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.get("https://api.ipify.org?format=json") as r:
            print(await r.json())


asyncio.run(main())

Step 5. Many requests at once

For parallel data collection use port 823 (or 824 for SOCKS5): every request gets a new address. To keep one IP for a series of requests, use a sticky port 10000-20000.

Step 6. Run the script and compare the IP from aiohttp with your own

The examples call https://api.ipify.org?format=json and print a dictionary with the ip key. It should contain the proxy address. If your own address is printed, the request went without the proxy: check that the proxy parameter is passed in the session.get() call you are running, or that the session connector is passed for SOCKS5.

Run the script several times in a row. On port 823 the addresses differ, on a sticky port they stay the same until the end of the session duration. When an exception appears instead of a dictionary, the class name points to the cause: see the error sections below.

A browser is not suitable for this check: the My IP page in it opens directly and shows the computer's address, not the script's.

Limiting concurrency and timeouts

aiohttp can easily start thousands of requests at once, and that is exactly what most often leads to 429 errors and timeouts. Limit the number of simultaneous requests with a semaphore and set an overall timeout for the session:

import asyncio
import aiohttp

PROXY = "http://USERNAME:PASSWORD@gw.prokso.com:823"
URLS = ["https://prokso.com/ip"] * 20


async def fetch(session, sem, url):
    async with sem:                                   # no more than 10 requests at once
        async with session.get(url, proxy=PROXY) as r:
            return r.status, await r.text()


async def main():
    sem = asyncio.Semaphore(10)
    timeout = aiohttp.ClientTimeout(total=30)
    async with aiohttp.ClientSession(timeout=timeout) as session:
        results = await asyncio.gather(*(fetch(session, sem, u) for u in URLS), return_exceptions=True)
    print(results)


asyncio.run(main())

return_exceptions=True keeps one failed request from cancelling the rest: the errors come back in the list of results, and you can retry them separately.

What the errors mean

  • ClientHttpProxyError, status 407. The proxy did not accept the username or password, or the traffic has run out.
  • ClientProxyConnectionError. Could not connect to the proxy: check the host and port.
  • asyncio.TimeoutError. The request did not fit within the timeout. Retry it or increase the limit.
  • ServerDisconnectedError. The connection dropped. A retry and lower concurrency usually help.

Codes 403 and 429 come from the site: what to do about them is described on the 429 error page.

One IP for a group of requests

Every request on port 823 goes out from a new IP. If several requests have to come from one address - a login, then the account pages - use a sticky port and a separate session for them: that way the cookies and the IP stay consistent.

HTTP, HTTPS or SOCKS5: which proxy URL aiohttp understands

The scheme at the start of a proxy URL describes the connection to the proxy, not to the website. That is why proxy="http://…" works for both http:// and https:// sites: for HTTPS, aiohttp opens a tunnel with the CONNECT method and the traffic to the site stays encrypted. You don't need a separate https:// proxy URL.

Proxy URLHow to connectProkso port
http://USERNAME:PASSWORD@gw.prokso.com:823built into aiohttp, the proxy= parameter823 - a new IP on every request
http://USERNAME:PASSWORD@gw.prokso.com:10000built into aiohttp, the proxy= parameter10000-20000 - sticky IP
socks5://USERNAME:PASSWORD@gw.prokso.com:824aiohttp-socks, ProxyConnector824 - a new IP on every connection
socks5://USERNAME:PASSWORD@gw.prokso.com:10000aiohttp-socks, ProxyConnector10000-20000 - sticky IP

A socks5:// URL in the proxy= parameter will not work: according to the aiohttp documentation, aiohttp itself supports HTTP proxies only. Connecting to the proxy over https:// (TLS to the proxy itself) has limited support in aiohttp, so use http:// with Prokso.

aiohttp-socks in detail: DNS on the proxy side, sticky IP and several proxies

Instead of a URL string, aiohttp-socks also takes the parameters one by one - handy for reading the password from an environment variable:

import asyncio
import os

import aiohttp
from aiohttp_socks import ProxyConnector, ProxyType


async def main():
    connector = ProxyConnector(
        proxy_type=ProxyType.SOCKS5,
        host="gw.prokso.com",
        port=10000,                      # sticky IP; 824 - a new IP for every connection
        username="LOGIN__cr.de",         # country in the username
        password=os.environ["PROKSO_PASSWORD"],
        rdns=True,                       # site names are resolved on the proxy side
    )
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.get("https://api.ipify.org?format=json") as r:
            print(await r.json())


asyncio.run(main())

rdns=True is the default for SOCKS5: the proxy resolves the site name, not your computer. That way your DNS server does not see which sites the script opens - more on DNS leaks.

The connector belongs to the session: all requests of one session go through one proxy. If you need several IPs or countries at once, create a separate session for each proxy line:

import asyncio

import aiohttp
from aiohttp_socks import ProxyConnector

LINES = [
    "socks5://LOGIN__cr.de:PASSWORD@gw.prokso.com:10001",
    "socks5://LOGIN__cr.pl:PASSWORD@gw.prokso.com:10002",
]


async def fetch_ip(line):
    async with aiohttp.ClientSession(connector=ProxyConnector.from_url(line)) as session:
        async with session.get("https://api.ipify.org?format=json") as r:
            return await r.json()


async def main():
    print(await asyncio.gather(*(fetch_ip(line) for line in LINES)))


asyncio.run(main())

Check that the addresses really differ: the script prints the IP of each session. How aiohttp reuses connections and why several requests in a row may leave from one address even on port 824 is explained in the article on keep-alive.

aiohttp-socks errors and what to check

  • ProxyConnectionError - the script could not reach gw.prokso.com: check the port and whether your network blocks it.
  • ProxyError - the proxy refused: a wrong username or password, SOCKS5 on HTTP port 823, or the plan is out of traffic.
  • ProxyTimeoutError - the proxy did not answer in time: retry the request or raise the timeout.
from aiohttp_socks import ProxyConnectionError, ProxyError, ProxyTimeoutError

try:
    async with session.get(url) as r:
        body = await r.text()
except ProxyConnectionError:
    ...  # gw.prokso.com:PORT is unreachable: check the port and your network
except ProxyError as e:
    ...  # the proxy refused: username, password, protocol/port or traffic balance
except ProxyTimeoutError:
    ...  # no answer in time: retry or raise the timeout

Errors of aiohttp itself with an HTTP proxy (for example, status 407) are covered above in "What the errors mean" and on the 407 Proxy Authentication Required page.

If the proxy does not work

FAQ

Does aiohttp read the proxy from environment variables?

Only if you create the session with trust_env=True - then it reads HTTP_PROXY and HTTPS_PROXY. Passing the proxy explicitly, as in the example, is more reliable.

How many concurrent requests can I run?

A plan allows up to 1,000 concurrent connections. Limit concurrency in your code (with a semaphore, for example) so you stay within the limit and don't overload the target site.

Can I set the proxy once for the whole session?

In current versions of aiohttp the session itself also accepts the proxy parameter. In older versions you have to pass it in every request.

How do I pass a password with @ or a colon in aiohttp?

Pass the username and password through urllib.parse.quote(..., safe="") and build the proxy URL from them. The aiohttp documentation marks the proxy_auth parameter with aiohttp.BasicAuth as deprecated since version 3.14, so a URL is better for new code.

How do I use an HTTPS proxy in aiohttp?

Pass a URL with the http:// scheme in the proxy parameter: for https sites aiohttp opens a CONNECT tunnel itself, and the traffic to the site stays encrypted. A proxy URL with https:// (TLS to the proxy) has limited support in aiohttp.

Does aiohttp support SOCKS5 without extra libraries?

No, aiohttp itself works with HTTP proxies only. For SOCKS5, install aiohttp-socks and pass a ProxyConnector to the session.

Which port should I use with aiohttp-socks?

824 is SOCKS5 with a new IP on every connection, 10000-20000 give a sticky IP for 1 to 120 minutes; sticky ports accept both HTTP and SOCKS5. Port 823 is HTTP only and does not work with SOCKS5.

Was this guide helpful?

Proxy not working? Check it in 6 steps

Install the Prokso app