Proxy connector for aiohttp
The `aiohttp-socks` package extends `aiohttp` by providing a proxy connector. It supports SOCKS4(a), SOCKS5(h), and HTTP (CONNECT) proxies, as well as proxy chaining, by leveraging the `python-socks` library for core proxy functionality. The current version is 0.11.0 and it maintains compatibility with recent `aiohttp` versions.
Warnings
- gotcha For SOCKS5 proxies, if connection issues (e.g., 'Connection refused') occur, ensure reverse DNS (rDNS) is enabled. This can be done by passing `rdns=True` to the `ProxyConnector` constructor or by using the `socks5h://` scheme in the proxy URL for `from_url`.
- breaking `aiohttp-socks` does not support setting a different proxy per request within a single `aiohttp.ClientSession`. The `ProxyConnector` is static for the session it's attached to. Attempting to pass a `proxy` argument to `session.get()` or similar methods will bypass `aiohttp-socks` or not work as expected.
- gotcha Older documentation or examples might refer to `SocksConnector` for creating proxy connections. The current and recommended class is `ProxyConnector`.
- breaking The minimum required Python version is 3.8 and `aiohttp` must be at least version 3.10.0. Using older versions can lead to `ImportError` or runtime incompatibilities.
Install
-
pip install aiohttp-socks
Imports
- ProxyConnector
from aiohttp_socks import ProxyConnector
- ChainProxyConnector
from aiohttp_socks import ChainProxyConnector
- ProxyType
from aiohttp_socks import ProxyType
Quickstart
import aiohttp
import asyncio
import os
from aiohttp_socks import ProxyType, ProxyConnector
async def fetch_with_proxy(url):
# Get proxy URL from environment variable for security and flexibility
# Example: socks5://user:password@127.0.0.1:1080
proxy_url = os.environ.get('AIOHTTP_SOCKS_PROXY_URL', 'socks5://127.0.0.1:1080')
connector = ProxyConnector.from_url(proxy_url)
async with aiohttp.ClientSession(connector=connector) as session:
async with session.get(url) as response:
response.raise_for_status()
text = await response.text()
print(f"Fetched via proxy: {url}\nStatus: {response.status}\nContent snippet: {text[:200]}...")
async def main():
print("Attempting to fetch with proxy...")
await fetch_with_proxy('http://httpbin.org/ip') # Use a simple endpoint to show IP
if __name__ == '__main__':
asyncio.run(main())