I have 2 network interfaces on my machine.
I want to use aiohttp for HTTP requests, but with control over which of the 2 interfaces the request goes through. This is equivalent to being able to specify my source IP address, since they are on different LANs.
Here is a solution using the non-async requests module:
import requests
def session_for_src_addr(addr: str) -> requests.Session:
session = requests.Session()
for prefix in ('http://', 'https://'):
session.get_adapter(prefix).init_poolmanager(
# those are default values from HTTPAdapter's constructor
connections=requests.adapters.DEFAULT_POOLSIZE,
maxsize=requests.adapters.DEFAULT_POOLSIZE,
# This should be a tuple of (address, port). Port 0 means auto-selection.
source_address=(addr, 0),
)
return session
# usage example:
s = session_for_src_addr('192.168.1.12')
s.get('https://httpbin.org/ip')
Any way to achieve similar with aiohttp.ClientSession()?