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 theaiohttp
library.proxy_url = 'http://user:[email protected]:3128'
: sets the proxy URL.aiohttp.ClientSession(connector=aiohttp.ProxyConnector(proxy_url=proxy_url))
: creates aClientSession
object with aProxyConnector
object as an argument.session.get('http://example.org')
: makes aGET
request tohttp://example.org
using the proxy.
Helpful links
Related
More of Python Aiohttp
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- Bearer token request example with Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to get response text with Python Aiohttp?
- How to rate limit with Python Aiohttp?
- How to check if a session is closed with Python Aiohttp?
- How to retry a request with Python Aiohttp?
See more codes...