</> Vikas Sharma

Requests Library Deep Dive - 6


Continuing the study of the requests module. Today, I am diving into requests/adapters.py, which implements the low-level connection management and is crucial for handling HTTP requests efficiently.

Key Concepts in requests/adapters.py

The HTTPAdapter Class

The HTTPAdapter class is responsible for:

Key Attributes of Session:

def __init__(self, pool_connections=10, pool_maxsize=10, max_retries=3, pool_block=False):
    self.max_retries = max_retries
    self.poolmanager = PoolManager(
        num_pools=pool_connections,
        maxsize=pool_maxsize,
        block=pool_block,
    )

Sending a request

The send method is the core of the HTTPAdapter class. It sends a PreparedRequest and returns a Response object.

Key Steps Inside send:

conn = self.poolmanager.connection_from_url(request.url)
response = conn.urlopen(
    method=request.method,
    url=request.url,
    body=request.body,
    headers=request.headers,
    retries=self.max_retries,
    timeout=timeout,
)
response = self.build_response(request, response)

Adapter lifecycle

self.adapters = {'http://': HTTPAdapter(), 'https://': HTTPAdapter()}
def get_adapter(self, url):
    for prefix, adapter in self.adapters.items():
        if url.lower().startswith(prefix):
            return adapter

Why Connection Pooling matters