Proxy connector for aiohttp

0.11.0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to configure an `aiohttp.ClientSession` to route requests through a SOCKS5 proxy using `ProxyConnector.from_url`. The proxy URL is retrieved from an environment variable for safe credentials handling. Ensure a proxy server is running at the specified address and port.

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())

view raw JSON →