CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-requests-toolbelt

A utility belt for advanced users of python-requests

Pending
Overview
Eval results
Files

authentication.mddocs/

Authentication

Advanced authentication handlers that automatically detect authentication methods and provide specialized authentication support including proxy authentication and compatibility with various authentication schemes.

Capabilities

Automatic Authentication Detection

Automatically detects and handles Basic and Digest authentication based on server responses.

class GuessAuth:
    """
    Authentication handler that guesses the auth type from WWW-Authenticate header.
    
    Parameters:
    - username: str, username for authentication
    - password: str, password for authentication
    """
    def __init__(self, username, password): ...
    
    # Instance attributes
    username: str             # Username for authentication
    password: str             # Password for authentication
    auth: Optional[AuthBase]  # Determined auth handler (set after detection)
    pos: Optional[int]        # Request body position for rewinding
    
    def handle_401(self, response, **kwargs):
        """
        Handle 401 Unauthorized responses by detecting auth type.
        
        Parameters:
        - response: Response object with 401 status
        - **kwargs: additional keyword arguments
        
        Returns:
        Response: new response with authentication
        """
    
    def __call__(self, request):
        """Apply authentication to request."""

Usage Examples

import requests
from requests_toolbelt import GuessAuth

# Automatic detection of Basic auth
response = requests.get(
    'https://httpbin.org/basic-auth/user/pass',
    auth=GuessAuth('user', 'pass')
)

# Works with Digest auth too
response = requests.get(
    'https://httpbin.org/digest-auth/auth/user/pass',
    auth=GuessAuth('user', 'pass')
)

# Use with session for multiple requests
session = requests.Session()
session.auth = GuessAuth('username', 'password')
response = session.get('https://protected-site.com/api/data')

Proxy Authentication

Handles both server authentication and proxy authentication simultaneously.

class GuessProxyAuth(GuessAuth):
    """
    Authentication handler for both server and proxy authentication.
    
    Parameters:
    - username: str, username for server authentication (optional)
    - password: str, password for server authentication (optional)
    - proxy_username: str, username for proxy authentication (optional)
    - proxy_password: str, password for proxy authentication (optional)
    """
    def __init__(self, username=None, password=None, proxy_username=None, proxy_password=None): ...
    
    # Instance attributes (inherited + new)
    username: Optional[str]             # Username for server auth
    password: Optional[str]             # Password for server auth
    proxy_username: Optional[str]       # Username for proxy auth
    proxy_password: Optional[str]       # Password for proxy auth
    auth: Optional[AuthBase]            # Determined server auth handler
    proxy_auth: Optional[AuthBase]      # Determined proxy auth handler
    pos: Optional[int]                  # Request body position for rewinding
    
    def handle_401(self, response, **kwargs):
        """Handle 401 Unauthorized responses (inherited from GuessAuth)."""
    
    def handle_407(self, response, **kwargs):
        """
        Handle 407 Proxy Authentication Required responses.
        
        Parameters:
        - response: Response object with 407 status
        - **kwargs: additional keyword arguments
        
        Returns:
        Response: new response with proxy authentication
        """
    
    def __call__(self, request):
        """Apply authentication to request (overrides GuessAuth)."""

Usage Examples

import requests
from requests_toolbelt.auth.guess import GuessProxyAuth

# Server authentication only
auth = GuessProxyAuth(username='user', password='pass')
response = requests.get('https://api.example.com/data', auth=auth)

# Proxy authentication only
auth = GuessProxyAuth(proxy_username='proxy_user', proxy_password='proxy_pass')
response = requests.get('https://api.example.com/data', auth=auth)

# Both server and proxy authentication
auth = GuessProxyAuth(
    username='server_user', 
    password='server_pass',
    proxy_username='proxy_user', 
    proxy_password='proxy_pass'
)
response = requests.get('https://api.example.com/data', auth=auth)

Authentication Handler

General-purpose authentication strategy handler for complex authentication workflows.

class AuthHandler(AuthBase):
    """
    Generic authentication handler supporting multiple domain-specific strategies.
    
    Parameters:
    - strategies: Dict[str, Union[Tuple[str, str], AuthBase]], mapping of domains to auth strategies
    """
    def __init__(self, strategies: Dict[str, Union[Tuple[str, str], AuthBase]]): ...
    
    # Instance attributes
    strategies: Dict[str, AuthBase]  # Normalized domain -> auth strategy mapping
    
    def __call__(self, request):
        """Apply appropriate authentication strategy based on request URL."""
    
    def __repr__(self) -> str:
        """Return string representation of AuthHandler."""
    
    def add_strategy(self, domain: str, strategy: Union[Tuple[str, str], AuthBase]) -> None:
        """
        Add a new domain and authentication strategy.
        
        Parameters:
        - domain: str, domain URL like 'https://api.github.com'
        - strategy: Union[Tuple[str, str], AuthBase], auth strategy (tuple converted to HTTPBasicAuth)
        """
    
    def get_strategy_for(self, url: str) -> AuthBase:
        """
        Retrieve the authentication strategy for a specified URL.
        
        Parameters:
        - url: str, full URL to get strategy for
        
        Returns:
        AuthBase: authentication strategy or NullAuthStrategy if none found
        """
    
    def remove_strategy(self, domain: str) -> None:
        """
        Remove domain and strategy from the collection.
        
        Parameters:
        - domain: str, domain to remove
        """
    
    @staticmethod
    def _key_from_url(url: str) -> str:
        """Extract normalized domain key from URL."""

class NullAuthStrategy(AuthBase):
    """No-operation authentication strategy."""
    
    def __call__(self, request):
        """Return request unchanged."""
    
    def __repr__(self) -> str:
        """Return string representation."""

Usage Examples

import requests
from requests_toolbelt.auth.handler import AuthHandler
from requests.auth import HTTPBasicAuth, HTTPDigestAuth

# Create handler with multiple domain strategies
auth_handler = AuthHandler({
    'https://api.github.com': ('github_user', 'github_token'),
    'https://api.bitbucket.org': HTTPBasicAuth('bb_user', 'bb_pass'),
    'https://secure-api.com': HTTPDigestAuth('digest_user', 'digest_pass')
})

# Use with requests
response = requests.get('https://api.github.com/user', auth=auth_handler)

# Add new strategy dynamically
auth_handler.add_strategy('https://newapi.com', ('new_user', 'new_pass'))

# Remove strategy
auth_handler.remove_strategy('https://api.bitbucket.org')

# Get strategy for specific URL
strategy = auth_handler.get_strategy_for('https://api.github.com/repos')

HTTP Proxy Digest Authentication

Specialized digest authentication for HTTP proxies.

class HTTPProxyDigestAuth(HTTPDigestAuth):
    """
    HTTP Proxy Digest Authentication handler with stale rejection tracking.
    
    Parameters:
    - *args: Arguments passed to HTTPDigestAuth (username, password)
    - **kwargs: Keyword arguments passed to HTTPDigestAuth
    """
    def __init__(self, *args, **kwargs): ...
    
    # Properties
    @property
    def stale_rejects(self) -> int:
        """
        Number of stale rejection attempts. Thread-safe property.
        
        Returns:
        int: count of stale rejections
        """
    
    @stale_rejects.setter
    def stale_rejects(self, value: int) -> None:
        """Set stale rejection count in thread-safe manner."""
    
    def init_per_thread_state(self) -> None:
        """Initialize per-thread state for digest authentication."""
    
    def handle_407(self, response, **kwargs):
        """
        Handle 407 Proxy Authentication Required responses.
        
        Parameters:
        - response: Response object with 407 status
        - **kwargs: additional keyword arguments
        
        Returns:
        Response: new response with proxy authentication applied
        
        Raises:
        IOError: if proxy violates RFC 7235 or credentials are invalid
        """
    
    def __call__(self, request):
        """Apply proxy digest authentication to request."""

Usage Examples

import requests
from requests_toolbelt.auth.http_proxy_digest import HTTPProxyDigestAuth

# Configure proxy with digest authentication
proxies = {
    'http': 'http://proxy.example.com:8080',
    'https': 'http://proxy.example.com:8080'
}

auth = HTTPProxyDigestAuth('proxy_user', 'proxy_password')

response = requests.get(
    'https://api.example.com/data',
    auth=auth,
    proxies=proxies
)

Digest Authentication Compatibility

Enhanced digest authentication with compatibility fixes for different versions of requests.

class HTTPDigestAuth:
    """
    Enhanced HTTP Digest Authentication with compatibility fixes.
    
    Parameters:
    - username: str, username for authentication
    - password: str, password for authentication
    """
    def __init__(self, username, password): ...
    
    def init_per_thread_state(self):
        """Initialize per-thread state for digest auth."""
    
    def handle_401(self, response, **kwargs):
        """Handle 401 Unauthorized responses with digest auth."""
    
    def __call__(self, request):
        """Apply digest authentication to request."""

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