Providing custom requests adapter code
The code snippet defines a requests HTTPAdapter subclass that binds to a specified source IP and measures time to first byte separately from full download time using streaming reads.
import time
import requests
from requests.adapters import HTTPAdapter
from urllib3 import PoolManager
class SourceIPAdapter(HTTPAdapter):
"""
A TransportAdapter that allows us to set the source IP address
for outgoing connections (useful on hosts with multiple interfaces).
"""
def __init__(self, source_ip, **kwargs):
self.source_ip = source_ip
super().__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
# Bind to the given source IP; port 0 lets the OS pick an ephemeral port
pool_kwargs['source_address'] = (self.source_ip, 0)
self.poolmanager = PoolManager(
num_pools=connections,
maxsize=maxsize,
block=block,
**pool_kwargs
)
def proxy_manager_for(self, proxy, **proxy_kwargs):
# Ensure proxy connections also use the specified source address
proxy_kwargs.setdefault("proxy_headers", {})
proxy_kwargs["source_address"] = (self.source_ip, 0)
return super().proxy_manager_for(proxy, **proxy_kwargs)
def check_site(url: str, source_ip: str = None, timeout: float = 10.0):
"""
Check the given URL, optionally binding the outgoing connection
to a specific source IP address. Returns a tuple of
(status_code, time_to_first_byte, total_time).
time_to_first_byte and total_time are in seconds.
"""
session = requests.Session()
if source_ip:
adapter = SourceIPAdapter(source_ip=source_ip)
session.mount("http://", adapter)
session.mount("https://", adapter)
# Start timing before the request is sent
start = time.perf_counter()
try:
# stream=True so we can measure TTFB separately
with session.get(url, stream=True, timeout=timeout) as resp:
# Read the first chunk to measure time to first byte
first_chunk = next(resp.iter_content(chunk_size=1), b'')
ttfb = time.perf_counter() - start
# Now consume the rest of the response to measure total time
for _ in resp.iter_content(chunk_size=8192):
pass
total_time = time.perf_counter() - start
return resp.status_code, ttfb, total_time
except Exception as e:
# In case of network errors, return None with the exception
return None, None, None, e
if __name__ == "__main__":
url_to_check = "https://www.example.com"
# Set to None if you don't need to bind to a specific interface
# Otherwise set to your desired source IP, e.g. "192.168.1.10"
bind_ip = None
result = check_site(url_to_check, source_ip=bind_ip, timeout=10)
if result and result[0] is not None:
status, ttfb, total = result[:3]
print(f"Status: {status}")
print(f"Time to first byte: {ttfb:.4f} s")
print(f"Total download time: {total:.4f} s")
else:
print("Request failed:", result)