CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-requests-toolbelt

A utility belt for advanced users of python-requests

Pending
Overview
Eval results
Files

adapters.mddocs/

HTTP Adapters

Specialized HTTPAdapter implementations that modify connection behavior for SSL protocol selection, source address binding, certificate verification, fingerprint validation, and socket configuration.

Capabilities

SSL Protocol Adapter

Select specific SSL/TLS protocol versions for connections.

class SSLAdapter:
    """
    HTTPAdapter for selecting SSL/TLS protocol version.
    
    Parameters:
    - ssl_version: SSL protocol version (ssl.PROTOCOL_* constants, optional)
    """
    def __init__(self, ssl_version=None, **kwargs): ...

Usage Examples

import requests
import ssl
from requests_toolbelt import SSLAdapter

session = requests.Session()

# Force TLS v1.2
session.mount('https://', SSLAdapter(ssl.PROTOCOL_TLSv1_2))

response = session.get('https://api.example.com/data')

# Use with specific endpoint
session.mount('https://secure-api.com', SSLAdapter(ssl.PROTOCOL_TLSv1_2))

Source Address Adapter

Bind connections to a specific source IP address.

class SourceAddressAdapter:
    """
    HTTPAdapter for binding to specific source address.
    
    Parameters:
    - source_address: tuple of (ip_address, port) or just ip_address string
    """
    def __init__(self, source_address): ...

Usage Examples

import requests
from requests_toolbelt import SourceAddressAdapter

session = requests.Session()

# Bind to specific IP (port chosen automatically)
session.mount('http://', SourceAddressAdapter('192.168.1.100'))
session.mount('https://', SourceAddressAdapter('192.168.1.100'))

# Bind to specific IP and port
session.mount('http://', SourceAddressAdapter(('192.168.1.100', 0)))

response = session.get('https://httpbin.org/ip')

X.509 Client Certificate Adapter

Use client certificates for authentication with automatic certificate validation.

class X509Adapter:
    """
    HTTPAdapter for X.509 client certificate authentication.
    
    Parameters:
    - cert_bytes: bytes, certificate data (keyword argument)
    - pk_bytes: bytes, private key data (keyword argument)
    - password: bytes or str, private key password (optional)
    - encoding: encoding format, default PEM encoding
    """
    def __init__(self, **kwargs): ...

def check_cert_dates(cert):
    """
    Verify that the supplied client cert is not invalid.
    
    Parameters:
    - cert: cryptography.x509.Certificate object
    
    Raises:
    ValueError: If certificate is expired (before not_valid_before or after not_valid_after)
    """

def create_ssl_context(cert_byes, pk_bytes, password=None, encoding=Encoding.PEM):
    """
    Create an SSL Context with the supplied cert/password.
    
    Note: Function has typo in parameter name - 'cert_byes' instead of 'cert_bytes'
    
    Parameters:
    - cert_byes: bytes, certificate data encoded using specified encoding
    - pk_bytes: bytes, private key data
    - password: bytes, private key passphrase (optional)
    - encoding: cryptography.hazmat.primitives.serialization.Encoding (default: Encoding.PEM)
    
    Returns:
    PyOpenSSLContext: SSL context object
    
    Raises:
    ValueError: If encoding is invalid or cert/key cannot be parsed
    """

Usage Examples

import requests
from requests_toolbelt.adapters.x509 import X509Adapter

# Load certificate and key
with open('client.crt', 'rb') as f:
    cert_data = f.read()

with open('client.key', 'rb') as f:
    key_data = f.read()

session = requests.Session()
session.mount('https://', X509Adapter(cert_bytes=cert_data, pk_bytes=key_data))

response = session.get('https://secure-api.example.com/data')

# With password-protected key
adapter = X509Adapter(cert_bytes=cert_data, pk_bytes=key_data, password='keypassword')
session.mount('https://', adapter)

SSL Fingerprint Verification

Verify SSL certificates by fingerprint to prevent man-in-the-middle attacks.

class FingerprintAdapter:
    """
    HTTPAdapter for SSL certificate fingerprint verification.
    
    Parameters:
    - fingerprint: str, expected certificate fingerprint (hex)
    """
    def __init__(self, fingerprint): ...

Usage Examples

import requests
from requests_toolbelt.adapters.fingerprint import FingerprintAdapter

# SHA-256 fingerprint verification
fingerprint = 'AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99'

session = requests.Session()
session.mount('https://api.example.com', FingerprintAdapter(fingerprint))

response = session.get('https://api.example.com/data')

Host Header SSL Adapter

Send custom Host header with SSL connections for specific hosting scenarios.

class HostHeaderSSLAdapter(HTTPAdapter):
    """
    A HTTPS Adapter that sets the hostname for certificate verification based on the Host header.
    
    This allows requesting an IP address directly via HTTPS without getting
    a "hostname doesn't match" exception by reading the Host header from the request.
    
    Parameters:
    - **kwargs: HTTPAdapter parameters (no special host parameter needed)
    """
    def __init__(self, **kwargs): ...
    
    def send(self, request, **kwargs):
        """Send request with Host header-based hostname verification."""

Usage Examples

import requests
from requests_toolbelt.adapters.host_header_ssl import HostHeaderSSLAdapter

session = requests.Session()
session.mount('https://', HostHeaderSSLAdapter())

# Request IP address directly with Host header for certificate verification
response = session.get(
    "https://93.184.216.34", 
    headers={"Host": "example.org"}
)

# Works with any IP/hostname mismatch scenario
response = session.get(
    "https://127.0.0.1:8443", 
    headers={"Host": "localhost.example.com"}
)

Socket Options Adapter

Configure socket-level options for fine-grained connection control.

class SocketOptionsAdapter:
    """
    HTTPAdapter for configuring socket options.
    
    Parameters:
    - socket_options: list of (level, optname, value) tuples
    """
    def __init__(self, socket_options): ...

class TCPKeepAliveAdapter:
    """
    HTTPAdapter that enables TCP keep-alive.
    
    Parameters:
    - idle: int, seconds before sending keep-alive probes (default: 60)
    - interval: int, interval between keep-alive probes (default: 20)
    - count: int, number of failed probes before declaring dead (default: 5)
    """
    def __init__(self, **kwargs): ...

Usage Examples

import requests
import socket
from requests_toolbelt.adapters.socket_options import SocketOptionsAdapter, TCPKeepAliveAdapter

# Custom socket options
socket_options = [
    (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
    (socket.SOL_TCP, socket.TCP_KEEPIDLE, 600),
]

session = requests.Session()
session.mount('http://', SocketOptionsAdapter(socket_options))
session.mount('https://', SocketOptionsAdapter(socket_options))

# TCP keep-alive with defaults
session = requests.Session()
adapter = TCPKeepAliveAdapter()
session.mount('http://', adapter)
session.mount('https://', adapter)

# Custom keep-alive settings
adapter = TCPKeepAliveAdapter(idle=300, interval=30, count=3)
session.mount('https://long-running-api.com', adapter)

response = session.get('https://long-running-api.com/stream')

Adapter Usage Patterns

# Multiple adapters for different endpoints
session = requests.Session()

# Different SSL versions for different sites
session.mount('https://old-api.com', SSLAdapter(ssl.PROTOCOL_TLSv1))
session.mount('https://new-api.com', SSLAdapter(ssl.PROTOCOL_TLSv1_2))

# Source address binding for specific routes
session.mount('https://internal-api.company.com', SourceAddressAdapter('10.0.1.100'))

# Client certificates for authentication
with open('client.crt', 'rb') as f:
    cert_data = f.read()
with open('client.key', 'rb') as f:
    key_data = f.read()

session.mount('https://secure-api.company.com', X509Adapter(cert_data, key_data))

# Fingerprint verification for critical endpoints
fingerprint = 'AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99'
session.mount('https://critical-api.company.com', FingerprintAdapter(fingerprint))

Install with Tessl CLI

npx tessl i tessl/pypi-requests-toolbelt

docs

adapters.md

authentication.md

cookies-exceptions.md

downloads.md

index.md

multipart.md

sessions-streaming.md

threading.md

utilities.md

tile.json