python-aiohttpHow to use a proxy with a Python aiohttp client?
Using a proxy with a Python aiohttp client is easy. All you need to do is to pass the proxy URL as an argument to the ProxyConnector class.
import aiohttp
proxy_url = 'http://user:[email protected]:3128'
async with aiohttp.ClientSession(connector=aiohttp.ProxyConnector(proxy_url=proxy_url)) as session:
async with session.get('http://example.org') as response:
print(response.status)
Output example
200
The code above creates a ClientSession object with a ProxyConnector object as an argument. The ProxyConnector object takes the proxy URL as an argument. The ClientSession object is then used to make a GET request to http://example.org using the proxy.
Code explanation
import aiohttp: imports theaiohttplibrary.proxy_url = 'http://user:[email protected]:3128': sets the proxy URL.aiohttp.ClientSession(connector=aiohttp.ProxyConnector(proxy_url=proxy_url)): creates aClientSessionobject with aProxyConnectorobject as an argument.session.get('http://example.org'): makes aGETrequest tohttp://example.orgusing the proxy.
Helpful links
Related
More of Python Aiohttp
- How to get response code with Python Aiohttp?
- How to use HTTP2 with Python Aiohttp?
- How to make parallel requests with Python Aiohttp?
- How to use keepalive with Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to set headers in Python Aiohttp?
- How to retry a request with Python Aiohttp?
- How to use Python Aiohttp and FastAPI?
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to check if a session is closed with Python Aiohttp?
See more codes...