### Installing requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/usage_guide.md This snippet demonstrates various installation options for the `requests-enhanced` library using `pip`. It covers basic installation, and installations with HTTP/2, HTTP/3, or all features enabled, allowing users to choose the required dependencies. ```bash pip install requests-enhanced # With HTTP/2 support pip install requests-enhanced[http2] # With HTTP/3 support pip install requests-enhanced[http3] # With all features pip install requests-enhanced[all] ``` -------------------------------- ### Quick Start with requests-enhanced Session (Python) Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/tutorial.md This snippet provides a quick start example for `requests-enhanced`. It initializes a `Session` object with automatic retries and performs a simple GET request to a GitHub API endpoint, then prints the JSON response. ```python from requests_enhanced import Session # Create a session with automatic retries session = Session(max_retries=3) # Make a simple GET request response = session.get('https://api.github.com') print(response.json()) ``` -------------------------------- ### Installing OAuth Dependencies for requests-enhanced (Bash) Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This command installs the `requests-enhanced` library along with its OAuth-specific dependencies (`requests-oauthlib` and `oauthlib`). It is the first step required to enable OAuth functionality. ```bash pip install requests-enhanced[oauth] ``` -------------------------------- ### Installing HTTP/3 Dependencies for requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md This command installs the `requests-enhanced` library along with its required HTTP/3 dependencies, simplifying the setup process for HTTP/3 support. ```bash pip install requests-enhanced[http3] ``` -------------------------------- ### Installing HTTP/2 Dependencies for requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md This command installs the `requests-enhanced` library along with its required HTTP/2 dependencies, simplifying the setup process for HTTP/2 support. ```bash pip install requests-enhanced[http2] ``` -------------------------------- ### Installing requests-enhanced with Optional Features (Bash) Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/tutorial.md This snippet demonstrates how to install the `requests-enhanced` library using pip. It shows basic installation, and how to include optional HTTP/2, HTTP/3, or all features by specifying extras in the `pip install` command. ```bash # Basic installation pip install requests-enhanced # With HTTP/2 support pip install requests-enhanced[http2] # With HTTP/3 support (experimental) pip install requests-enhanced[http3] # All features pip install requests-enhanced[all] ``` -------------------------------- ### Installing requests-enhanced Library Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/quick-reference.md This section provides commands for installing the `requests-enhanced` Python library using `pip`. It includes options for basic installation, and additional dependencies for HTTP/2, HTTP/3, or all features. ```bash pip install requests-enhanced # Basic pip install requests-enhanced[http2] # With HTTP/2 pip install requests-enhanced[http3] # With HTTP/3 pip install requests-enhanced[all] # Everything ``` -------------------------------- ### Creating and Using Sessions in Requests Enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/README.md This example demonstrates how to import and initialize `Session` objects from `requests_enhanced`. It shows how to configure sessions for default settings, HTTP/2, and HTTP/3, and how to perform a basic GET request and parse the JSON response. ```python from requests_enhanced import Session # Create a session with default retry and timeout settings session = Session() # Use HTTP/2 protocol http2_session = Session(http_version="2") # Use HTTP/3 with automatic fallback http3_session = Session(http_version="3") # Simple GET request response = session.get("https://api.example.com/resources") print(response.json()) ``` -------------------------------- ### Installing requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-integration-summary.md Provides the basic command to install the `requests-enhanced` library using pip, without optional dependencies. ```bash pip install requests-enhanced ``` -------------------------------- ### Installing Requests Enhanced with Optional Features Source: https://github.com/khollingworth/requests-enhanced/blob/main/README.md This snippet provides commands for installing the `requests-enhanced` library from PyPI, including options for specific features like HTTP/2, HTTP/3, OAuth, or all features. It also shows how to set up the project for local development. ```bash # Basic installation from PyPI pip install requests-enhanced # With HTTP/2 support pip install requests-enhanced[http2] # With HTTP/3 support pip install requests-enhanced[http3] # With OAuth support pip install requests-enhanced[oauth] # With all features pip install requests-enhanced[all] # Includes HTTP/2, HTTP/3, and OAuth # For development git clone https://github.com/khollingworth/requests-enhanced.git cd requests-enhanced pip install -e ".[dev]" ``` -------------------------------- ### Installing requests-enhanced with pip Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/index.md This snippet demonstrates how to install the `requests-enhanced` library using pip. It shows the basic installation and how to include optional features like HTTP/2, HTTP/3, or OAuth support by specifying extra dependencies in square brackets, or install all features at once. ```bash # Basic installation pip install requests-enhanced # With HTTP/2 support pip install requests-enhanced[http2] # With HTTP/3 support pip install requests-enhanced[http3] # With OAuth support pip install requests-enhanced[oauth] # Full installation with all features pip install requests-enhanced[all] ``` -------------------------------- ### Installing requests-enhanced with OAuth Support Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-integration-summary.md Provides the command to install the `requests-enhanced` library along with its optional OAuth dependencies using pip. ```bash pip install requests-enhanced[oauth] ``` -------------------------------- ### Making a GET request with requests-enhanced Session Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/index.md This example illustrates how to use the `Session` object from `requests-enhanced` to make an HTTP GET request. It demonstrates setting a preferred HTTP version (e.g., HTTP/3) and highlights the library's automatic protocol negotiation and fallback mechanism, printing the status code and the actual protocol used. ```python from requests_enhanced import Session # Create a session with HTTP/3 support (falls back to HTTP/2 and HTTP/1.1) session = Session(http_version=3) # Make a request - protocol negotiation happens automatically response = session.get('https://example.com') print(f"Response received with status: {response.status_code}") print(f"Protocol used: {response.raw.version}") ``` -------------------------------- ### Implementing Full OAuth 1.0 Authentication Flow (Python) Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This comprehensive example illustrates the complete OAuth 1.0/1.1 authentication flow, including fetching a request token, obtaining user authorization, exchanging for an access token, and making authenticated requests. It covers all necessary steps for a typical OAuth 1.0 client application. ```python from requests_enhanced import OAuth1EnhancedSession # Step 1: Create session with consumer credentials session = OAuth1EnhancedSession( client_key='your_consumer_key', client_secret='your_consumer_secret' ) # Step 2: Fetch request token request_token = session.fetch_request_token( 'https://api.example.com/oauth/request_token' ) print(f"Request Token: {request_token['oauth_token']}") # Step 3: Get authorization URL auth_url = session.authorization_url( 'https://api.example.com/oauth/authorize' ) print(f"Visit this URL to authorize: {auth_url}") # Step 4: After user authorization, fetch access token # (You'll get the verifier from the callback URL) access_token = session.fetch_access_token( 'https://api.example.com/oauth/access_token', verifier='verifier_from_callback' ) # Step 5: Make authenticated requests response = session.get('https://api.example.com/protected_resource') print(response.json()) ``` -------------------------------- ### Performing Basic HTTP Requests with requests-enhanced Session Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/usage_guide.md This snippet shows how to create a `Session` object from `requests_enhanced` for making basic GET and POST requests. It demonstrates retrieving JSON data from a GET request and sending JSON payloads with a POST request, leveraging default retry and timeout settings. ```python from requests_enhanced import Session # Create a session with default retry and timeout settings session = Session() # Simple GET request response = session.get("https://api.example.com/resources") print(response.json()) # POST request with JSON data data = {"name": "example", "value": 42} response = session.post("https://api.example.com/resources", json=data) print(response.status_code) ``` -------------------------------- ### Installing HTTP/2 Dependencies - Bash Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md Provides the command-line instruction to install the additional dependencies required for HTTP/2 support in `requests-enhanced` using pip, leveraging the `[http2]` extra. ```Bash pip install requests-enhanced[http2] ``` -------------------------------- ### Manually Installing aioquic Dependency for HTTP/3 Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md This command manually installs the `aioquic` package, which is the core dependency required for HTTP/3 support in the `requests-enhanced` library. ```bash pip install aioquic ``` -------------------------------- ### Uploading Files with requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/quick-reference.md Provides examples for uploading single and multiple files using `requests-enhanced`. It shows how to prepare the `files` dictionary for a `POST` request, including specifying filenames, file objects, and content types for multiple files. ```python # Single file with open('file.txt', 'rb') as f: files = {'file': f} response = session.post(url, files=files) # Multiple files files = [ ('files', ('file1.txt', open('file1.txt', 'rb'), 'text/plain')), ('files', ('file2.txt', open('file2.txt', 'rb'), 'text/plain')) ] response = session.post(url, files=files) ``` -------------------------------- ### Performing Basic HTTP Requests with requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/quick-reference.md Demonstrates fundamental HTTP operations (GET, POST, PUT, DELETE, PATCH) using the `Session` object from `requests-enhanced`. It shows how to initialize a session and make various types of requests to an API endpoint. ```python from requests_enhanced import Session # Create session session = Session() # Make requests r = session.get('https://api.example.com') r = session.post('https://api.example.com', json={'key': 'value'}) r = session.put('https://api.example.com', data='content') r = session.delete('https://api.example.com/item/1') r = session.patch('https://api.example.com', json={'update': 'value'}) ``` -------------------------------- ### Resolving Missing Dependencies in requests-enhanced OAuth Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet shows the solution for an `OAuthNotAvailableError` which indicates a missing `requests-oauthlib` package, a required dependency for OAuth functionality in `requests-enhanced`. The provided solution is to install the package using `pip install requests-enhanced[oauth]`. ```Shell pip install requests-enhanced[oauth] ``` -------------------------------- ### Manually Installing HTTP/2 Dependencies - Bash Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md Provides the command-line instruction to manually install the individual packages (`h2`, `hyperframe`, `hpack`) that constitute the HTTP/2 dependencies for `requests-enhanced`. ```Bash pip install h2 hyperframe hpack ``` -------------------------------- ### Package Build Verification Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-integration-summary.md Confirms the successful build of source and wheel distributions, correct installation of OAuth dependencies, and verification of imports and backward compatibility. ```Text ✅ Source distribution builds successfully ✅ Wheel distribution builds successfully ✅ OAuth dependencies install correctly ✅ All imports work as expected ✅ No breaking changes detected ``` -------------------------------- ### Setting Up Development Environment for requests-enhanced (Bash) Source: https://github.com/khollingworth/requests-enhanced/blob/main/README.md This snippet provides a sequence of Bash commands to set up a local development environment for the `requests-enhanced` project. It includes cloning the repository, creating and activating a Python virtual environment, and installing development dependencies. ```bash # Clone the repository git clone https://github.com/khollingworth/requests-enhanced.git cd requests-enhanced # Create a virtual environment (recommended) python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install development dependencies pip install -e ".[dev]" ``` -------------------------------- ### Using requests-enhanced JSON Utility Functions Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/usage_guide.md This snippet illustrates the use of `json_get` and `json_post` utility functions from `requests_enhanced.utils`. These functions simplify common HTTP operations by automatically handling JSON parsing for GET requests and JSON serialization for POST requests, streamlining API interactions. ```python from requests_enhanced.utils import json_get, json_post # GET request that automatically returns JSON data = json_get("https://api.example.com/resources") # POST request with automatic JSON handling result = json_post("https://api.example.com/resources", data={"name": "example"}) ``` -------------------------------- ### Combining OAuth 1.0 with Enhanced Session Features (Python) Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This example demonstrates how to integrate OAuth 1.0 authentication with other advanced features of `requests-enhanced` like `timeout`, `max_retries`, and `http_version`. It allows for robust and efficient authenticated requests. ```python from requests_enhanced import OAuth1EnhancedSession session = OAuth1EnhancedSession( client_key='your_consumer_key', client_secret='your_consumer_secret', resource_owner_key='your_access_token', resource_owner_secret='your_access_token_secret', # Enhanced session features timeout=30, max_retries=3, http_version='2' # Use HTTP/2 ) # Authenticated request with retry and timeout response = session.get('https://api.example.com/data') ``` -------------------------------- ### Implementing OAuth 2.0 Authorization Code Flow (Python) Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This example details the OAuth 2.0 Authorization Code flow, including generating an authorization URL, handling the redirect, and exchanging the authorization code for an access token. It's the most common flow for web applications. ```python from requests_enhanced import OAuth2EnhancedSession # Step 1: Create session session = OAuth2EnhancedSession( client_id='your_client_id', redirect_uri='https://your-app.com/callback', scope=['read', 'write'] # Requested scopes ) # Step 2: Get authorization URL auth_url, state = session.authorization_url( 'https://api.example.com/oauth/authorize' ) print(f"Visit this URL to authorize: {auth_url}") print(f"State: {state}") # Step 3: After user authorization, exchange code for token # (You'll get the authorization_response from your callback URL) token = session.fetch_token( 'https://api.example.com/oauth/token', authorization_response='https://your-app.com/callback?code=auth_code&state=state', client_secret='your_client_secret' # Required for confidential clients ) # Step 4: Make authenticated requests response = session.get('https://api.example.com/user') print(response.json()) ``` -------------------------------- ### Example of Configuring requests-enhanced Logger in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md This example demonstrates how to initialize a logger and then configure it using `configure_logger` from `requests_enhanced`. It sets the logging level to `DEBUG` for the 'requests_enhanced' logger, enabling detailed output for debugging purposes. ```python import logging from requests_enhanced.logging import configure_logger logger = logging.getLogger("requests_enhanced") configure_logger(logger, level=logging.DEBUG) ``` -------------------------------- ### Initializing OAuth 1.0 Session with requests-enhanced (Python) Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet demonstrates the basic initialization of an `OAuth1EnhancedSession` using consumer key and secret. It sets up a session ready for OAuth 1.0/1.1 authentication. ```python from requests_enhanced import OAuth1EnhancedSession # Create an OAuth 1.0 session session = OAuth1EnhancedSession( client_key='your_consumer_key', client_secret='your_consumer_secret' ) ``` -------------------------------- ### Using OAuth 2.0 with Enhanced Session Features in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This example demonstrates initializing `OAuth2EnhancedSession` with additional features like `timeout`, `max_retries`, and `http_version`. These features enhance the robustness and performance of authenticated requests. Dependencies include `requests_enhanced`. ```Python from requests_enhanced import OAuth2EnhancedSession session = OAuth2EnhancedSession( client_id='your_client_id', token=token, # Enhanced session features timeout=45, max_retries=5, http_version='3' # Use HTTP/3 if available ) # Authenticated request with enhanced features response = session.get('https://api.example.com/data') ``` -------------------------------- ### Manually Installing h2 Dependency for HTTP/2 Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md This command manually installs the `h2` package, which is the core dependency required for HTTP/2 support in the `requests-enhanced` library. ```bash pip install h2 ``` -------------------------------- ### Configuring OAuth 1.0a for Twitter with requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This example details how to use `OAuth1EnhancedSession` for Twitter's OAuth 1.0a authentication. It covers the steps for fetching a request token, generating an authorization URL, exchanging the verifier for an access token, and making authenticated API requests to Twitter. ```Python from requests_enhanced import OAuth1EnhancedSession session = OAuth1EnhancedSession( client_key='your_twitter_api_key', client_secret='your_twitter_api_secret' ) # Request token request_token = session.fetch_request_token( 'https://api.twitter.com/oauth/request_token', realm='your_app_name' ) # Authorization URL auth_url = session.authorization_url( 'https://api.twitter.com/oauth/authorize' ) # Access token (after user authorization) access_token = session.fetch_access_token( 'https://api.twitter.com/oauth/access_token', verifier='pin_from_user' ) # API requests user = session.get('https://api.twitter.com/1.1/account/verify_credentials.json').json() ``` -------------------------------- ### Configuring OAuth2 for GitHub with requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This example shows how to set up an `OAuth2EnhancedSession` for GitHub, including defining client ID, redirect URI, and scopes. It covers the full OAuth 2.0 flow: generating an authorization URL, exchanging the authorization response for an access token, and making authenticated API calls. ```Python from requests_enhanced import OAuth2EnhancedSession session = OAuth2EnhancedSession( client_id='your_github_client_id', redirect_uri='http://localhost:8080/callback', scope=['user', 'repo'] ) # Authorization URL auth_url, state = session.authorization_url( 'https://github.com/login/oauth/authorize' ) # Token exchange token = session.fetch_token( 'https://github.com/login/oauth/access_token', authorization_response=callback_url, client_secret='your_github_client_secret' ) # API requests user = session.get('https://api.github.com/user').json() repos = session.get('https://api.github.com/user/repos').json() ``` -------------------------------- ### Enabling HTTP/2 and HTTP/3 Support in requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/usage_guide.md This snippet illustrates how to enable HTTP/2 and HTTP/3 support in `requests-enhanced` sessions. It shows creating a session with a specified HTTP version or explicitly mounting `HTTP2Adapter` for specific protocols, demonstrating advanced protocol handling and fallback mechanisms. ```python from requests_enhanced import Session from requests_enhanced.adapters import HTTP2Adapter, HTTP3Adapter # Create a session with HTTP/2 support session = Session(http_version=2) response = session.get("https://http2.example.com") # Or explicitly mount HTTP/2 adapter session = Session() session.mount("https://", HTTP2Adapter()) response = session.get("https://http2.example.com") # Using HTTP/3 with automatic fallback to HTTP/2 and HTTP/1.1 session = Session(http_version=3) response = session.get("https://http3.example.com") ``` -------------------------------- ### Handling Exceptions in requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/quick-reference.md Provides examples of catching specific exceptions raised by `requests-enhanced`, such as `RequestTimeoutError`, `RequestRetryError`, `ConnectionError`, and `HTTPError`, along with the base `RequestException`. This allows for robust error management in HTTP requests. ```python from requests_enhanced.exceptions import ( RequestException, # Base exception RequestTimeoutError, # Timeout occurred RequestRetryError, # All retries failed ConnectionError, # Connection issues HTTPError # HTTP error status ) try: response = session.get(url) response.raise_for_status() except RequestTimeoutError: print("Request timed out") except RequestRetryError as e: print(f"Failed after retries: {e}") except HTTPError as e: print(f"HTTP error: {e}") except RequestException as e: print(f"Request failed: {e}") ``` -------------------------------- ### Making Various HTTP Requests with requests-enhanced (Python) Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/tutorial.md This snippet illustrates how to perform common HTTP methods (GET, POST, PUT, DELETE, PATCH) using a `requests-enhanced` Session. It shows how to send JSON data with POST, PUT, and PATCH requests. ```python from requests_enhanced import Session session = Session() # GET request response = session.get('https://httpbin.org/get') # POST request with JSON data data = {'name': 'John', 'age': 30} response = session.post('https://httpbin.org/post', json=data) # PUT request response = session.put('https://httpbin.org/put', json=data) # DELETE request response = session.delete('https://httpbin.org/delete') # PATCH request response = session.patch('https://httpbin.org/patch', json={'name': 'Jane'}) ``` -------------------------------- ### Manually Mounting HTTP/3 Adapter with Automatic Fallback Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md This example demonstrates how to manually mount the `HTTP3Adapter` to a session, enabling HTTP/3 support with automatic fallback to HTTP/2 and HTTP/1.1 if HTTP/3 is unavailable or fails. It also includes a check for HTTP/3 availability. ```python # HTTP/3 Support with automatic fallback from requests_enhanced import Session, HTTP3Adapter, HTTP3_AVAILABLE # Check if HTTP/3 is available print(f"HTTP/3 support available: {HTTP3_AVAILABLE}") # Mount HTTP/3 adapter (with automatic fallback) session = Session() http3_adapter = HTTP3Adapter() session.mount("https://", http3_adapter) # Will use HTTP/3 if available, falling back to HTTP/2 and HTTP/1.1 if not response = session.get("https://example.com") ``` -------------------------------- ### Using Global Functions with requests-enhanced as requests in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/tutorial.md This example demonstrates how `requests-enhanced` can be imported and aliased as `requests`, allowing users to continue using the familiar global function API (e.g., `requests.get()`, `requests.post()`) while benefiting from `requests-enhanced`'s improved features and defaults. ```Python # You can also use the familiar requests API import requests_enhanced as requests response = requests.get('https://api.example.com') response = requests.post('https://api.example.com', json={'data': 'value'}) ``` -------------------------------- ### Using HTTP/3 with requests-enhanced Session in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/tutorial.md This snippet demonstrates how to enable and use HTTP/3 (QUIC) with `requests-enhanced`. It checks for HTTP/3 availability, mounts an `HTTP3Adapter` to a `Session` for a specific domain, and then makes a GET request. Requests will automatically fall back to HTTP/2 if HTTP/3 fails. ```Python from requests_enhanced import Session, HTTP3Adapter from requests_enhanced.adapters import HTTP3_AVAILABLE if HTTP3_AVAILABLE: session = Session() # Mount HTTP/3 adapter http3_adapter = HTTP3Adapter() session.mount("https://quic-enabled-site.com", http3_adapter) # Requests will use HTTP/3 with automatic fallback to HTTP/2 response = session.get('https://quic-enabled-site.com/api/data') else: print("HTTP/3 dependencies not installed") ``` -------------------------------- ### Enabling Debug Logging for requests-enhanced OAuth Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet demonstrates how to enable debug logging for `requests-enhanced` sessions. By setting the logging level to `DEBUG`, developers can get detailed information about OAuth requests, which is crucial for troubleshooting authentication issues. ```Python import logging from requests_enhanced import OAuth2EnhancedSession # Enable debug logging logging.basicConfig(level=logging.DEBUG) session = OAuth2EnhancedSession(client_id='your_client_id') # OAuth requests will now show detailed debug information ``` -------------------------------- ### Migrating from requests-oauthlib to requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet illustrates the migration path from `requests-oauthlib` to `requests-enhanced`. It highlights that `requests-enhanced` maintains API compatibility while adding enhanced features like `timeout`, `max_retries`, and `http_version`, simplifying the transition for existing projects. ```Python # Old: requests-oauthlib from requests_oauthlib import OAuth1Session, OAuth2Session # New: requests-enhanced from requests_enhanced import OAuth1EnhancedSession, OAuth2EnhancedSession # The API is the same, but you get additional enhanced features session = OAuth2EnhancedSession( client_id='client_id', # Plus enhanced features: timeout=30, max_retries=3, http_version='2' ) ``` -------------------------------- ### Checking HTTP/2 Availability - Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md Illustrates how to use the `HTTP2_AVAILABLE` boolean flag to programmatically check if the necessary HTTP/2 dependencies are installed, providing a message to the user based on availability. ```Python if HTTP2_AVAILABLE: print("HTTP/2 support is available") else: print("HTTP/2 dependencies not installed. Install with: pip install requests-enhanced[http2]") ``` -------------------------------- ### Setting Timeouts for requests-enhanced in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/tutorial.md This example demonstrates how to set timeouts for HTTP requests using `requests-enhanced` to prevent hanging connections. Timeouts can be configured globally for a `Session` or specified per-request, allowing separate values for connection establishment and read operations. ```Python # Always set timeouts to prevent hanging requests session = Session(timeout=30) # Or per-request timeout response = session.get('https://api.example.com', timeout=(3.05, 27)) # (connection timeout, read timeout) ``` -------------------------------- ### Checking HTTP/3 Availability in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md This snippet demonstrates how to use the `HTTP3_AVAILABLE` boolean flag to programmatically check if HTTP/3 dependencies are installed, providing guidance to the user if they are not. ```python if HTTP3_AVAILABLE: print("HTTP/3 support is available") else: print("HTTP/3 dependencies not installed. Install with: pip install requests-enhanced[http3]") ``` -------------------------------- ### Implementing Basic Error Handling with requests-enhanced in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/tutorial.md This example shows how to handle common exceptions when making requests with `requests-enhanced`, including timeouts, retries, HTTP errors (4xx/5xx), and general request failures. It uses a `Session` configured with retries and a timeout, and `response.raise_for_status()` to convert bad status codes into `HTTPError`. ```Python from requests_enhanced import Session from requests_enhanced.exceptions import ( RequestException, RequestTimeoutError, RequestRetryError, HTTPError ) session = Session(max_retries=3, timeout=10) try: response = session.get('https://api.example.com/data') response.raise_for_status() # Raise exception for bad status codes data = response.json() except RequestTimeoutError: print("Request timed out") except RequestRetryError as e: print(f"Failed after {session.max_retries} retries: {e}") except HTTPError as e: print(f"HTTP error occurred: {e}") except RequestException as e: print(f"Request failed: {e}") ``` -------------------------------- ### Initializing OAuth 2.0 Session with requests-enhanced (Python) Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet illustrates the basic initialization of an `OAuth2EnhancedSession` using only the client ID. It prepares a session for OAuth 2.0 authentication flows. ```python from requests_enhanced import OAuth2EnhancedSession # Create an OAuth 2.0 session session = OAuth2EnhancedSession( client_id='your_client_id' ) ``` -------------------------------- ### Importing Utility Functions in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md This line imports `json_get` and `json_post` from `requests_enhanced.utils`, providing convenient functions for making JSON-based GET and POST requests. ```python from requests_enhanced.utils import json_get, json_post ``` -------------------------------- ### Implementing OAuth 2.0 Client Credentials Flow in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet illustrates how to implement the OAuth 2.0 Client Credentials flow for server-to-server authentication using `requests_enhanced`. It shows fetching a token with `fetch_token` and then making authenticated requests. Dependencies include `requests_enhanced`. ```Python from requests_enhanced import OAuth2EnhancedSession session = OAuth2EnhancedSession(client_id='your_client_id') # Fetch token using client credentials token = session.fetch_token( 'https://api.example.com/oauth/token', client_secret='your_client_secret', grant_type='client_credentials', scope=['api:read', 'api:write'] ) # Make authenticated requests response = session.get('https://api.example.com/data') ``` -------------------------------- ### Handling Specific Errors in requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/usage_guide.md This snippet demonstrates how to handle specific exceptions like `RequestTimeoutError` and `RequestRetryError` raised by `requests-enhanced`. It shows a `try-except` block to catch these errors and access the `original_exception` attribute for detailed debugging and error analysis. ```python from requests_enhanced import Session from requests_enhanced.exceptions import RequestTimeoutError, RequestRetryError try: session = Session() response = session.get("https://api.example.com/resources") data = response.json() except RequestTimeoutError as e: print(f"Request timed out: {e}") print(f"Original exception: {e.original_exception}") except RequestRetryError as e: print(f"Retry failed: {e}") print(f"Original exception: {e.original_exception}") ``` -------------------------------- ### Quick OAuth 2.0 Example with Enhanced Session Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-integration-summary.md Demonstrates how to use `OAuth2EnhancedSession` to perform an OAuth 2.0 authorization code flow, including session creation with enhanced features (HTTP/2, retries, timeouts), obtaining an authorization URL, fetching an access token, and making authenticated API requests. ```python from requests_enhanced import OAuth2EnhancedSession # Create OAuth 2.0 session with enhanced features session = OAuth2EnhancedSession( client_id='your_client_id', redirect_uri='http://localhost:8080/callback', scope=['user', 'repo'], # Enhanced features http_version='2', # Use HTTP/2 max_retries=3, # Auto-retry timeout=30 # Timeout handling ) # Get authorization URL auth_url, state = session.authorization_url( 'https://github.com/login/oauth/authorize' ) # Exchange code for token (after user authorization) token = session.fetch_token( 'https://github.com/login/oauth/access_token', authorization_response=callback_url, client_secret='your_client_secret' ) # Make authenticated requests with all enhanced features response = session.get('https://api.github.com/user') user_data = response.json() ``` -------------------------------- ### Managing Sessions for Connection Pooling in requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/usage_guide.md This snippet demonstrates two ways to manage sessions in `requests-enhanced` for efficient connection pooling: using a context manager for automatic cleanup and explicitly creating/closing a session for multiple requests. This optimizes performance by reusing underlying TCP connections. ```python from requests_enhanced import Session # Using context manager for automatic cleanup with Session() as session: response = session.get("https://api.example.com/resources") # Session will be automatically closed when exiting the with block # Reusing a session for multiple requests (connection pooling) session = Session() for i in range(10): response = session.get(f"https://api.example.com/resources/{i}") # Uses the same connection pool for better performance session.close() # Explicitly close when done ``` -------------------------------- ### Using requests-enhanced Session with HTTP Versions - Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md Demonstrates how to create and use `Session` objects with different HTTP protocol versions (1.1, 2, and 3) and custom timeout/retry settings. It shows how to make GET requests using these sessions. ```Python # Standard session with HTTP/1.1 session = Session(timeout=(5, 30), max_retries=5) response = session.get("https://api.example.com/resources") # HTTP/2 enabled session for improved performance session_http2 = Session(timeout=(5, 30), max_retries=5, http_version="2") response = session_http2.get("https://api.example.com/resources") # HTTP/3 enabled session with automatic fallback to HTTP/2 and HTTP/1.1 session_http3 = Session(timeout=(5, 30), max_retries=5, http_version="3") response = session_http3.get("https://api.example.com/resources") ``` -------------------------------- ### Implementing Secure Token Storage to File in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet provides functions for securely saving and loading OAuth tokens to/from a file. It uses `pathlib` for cross-platform path handling and `os.chmod` to set restrictive file permissions (0o600) for security. Dependencies include `json`, `os`, and `pathlib`. ```Python import json import os from pathlib import Path def save_token_to_file(token, filename='token.json'): """Securely save token to file""" token_path = Path.home() / '.config' / 'myapp' / filename token_path.parent.mkdir(parents=True, exist_ok=True) with open(token_path, 'w') as f: json.dump(token, f) # Set restrictive permissions os.chmod(token_path, 0o600) def load_token_from_file(filename='token.json'): """Load token from file""" token_path = Path.home() / '.config' / 'myapp' / filename if token_path.exists(): with open(token_path, 'r') as f: return json.load(f) return None ``` -------------------------------- ### Using Sessions for Efficient Connection Reuse in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/tutorial.md This snippet illustrates the best practice of using `requests-enhanced` `Session` objects for making multiple requests. Sessions reuse TCP connections, which is more efficient than creating a new connection for each request, as shown with the less efficient `requests` example. ```Python # Good - reuses connections with Session() as session: for url in urls: response = session.get(url) # Less efficient - creates new connection each time import requests for url in urls: response = requests.get(url) ``` -------------------------------- ### Using Automatic HTTP/2 Fallback with requests-enhanced Session Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/api_reference.md This example shows how to create a session requesting HTTP/2. The library automatically falls back to HTTP/1.1 if HTTP/2 dependencies are missing or the server doesn't support it, ensuring robust connection handling. It also demonstrates checking for HTTP/2 availability. ```python from requests_enhanced import Session, HTTP2_AVAILABLE # Check if HTTP/2 is available print(f"HTTP/2 support available: {HTTP2_AVAILABLE}") # Create session with HTTP/2 requested session = Session(http_version="2") # If HTTP/2 dependencies are not available, this will use HTTP/1.1 response = session.get("https://example.com") ``` -------------------------------- ### Configuring Timeouts in requests-enhanced Session Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/usage_guide.md This snippet shows how to set global and per-request timeouts for a `requests-enhanced` session. It demonstrates configuring connect and read timeouts for the entire session and overriding them for specific requests, ensuring fine-grained control over request duration. ```python from requests_enhanced import Session # Set custom timeout (connect_timeout, read_timeout) session = Session(timeout=(3.05, 27)) # Timeout will be applied to all requests response = session.get("https://api.example.com/resources") # Override timeout for a specific request response = session.get("https://api.example.com/slow-resource", timeout=(5, 60)) ``` -------------------------------- ### Configuring Custom Logging for requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/usage_guide.md This snippet demonstrates how to configure custom logging for the `requests_enhanced` library. It shows how to retrieve the library's dedicated logger and use `configure_logger` to set a custom log level and format, enabling detailed debugging and monitoring of HTTP requests. ```python import logging from requests_enhanced.logging import configure_logger # Get the requests_enhanced logger logger = logging.getLogger("requests_enhanced") # Configure with custom format and level configure_logger(logger, level=logging.DEBUG, log_format="%(asctime)s - %(levelname)s - %(message)s") ``` -------------------------------- ### Handling Specific HTTP Status Codes in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/tutorial.md This snippet demonstrates how to explicitly check and handle different HTTP status codes returned in a response. It provides examples for success (200), not found (404), rate limiting (429, including `Retry-After` header), and server errors (5xx). ```Python response = session.get('https://api.example.com/resource') if response.status_code == 200: print("Success!") elif response.status_code == 404: print("Resource not found") elif response.status_code == 429: # Rate limited - check for Retry-After header retry_after = response.headers.get('Retry-After', 60) print(f"Rate limited. Retry after {retry_after} seconds") elif response.status_code >= 500: print("Server error") ``` -------------------------------- ### Using Pre-existing OAuth 1.0 Access Tokens (Python) Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet shows how to initialize an `OAuth1EnhancedSession` directly with existing access tokens (resource owner key and secret). This is useful when an application has already completed the authorization flow and stored the tokens for future use. ```python from requests_enhanced import OAuth1EnhancedSession session = OAuth1EnhancedSession( client_key='your_consumer_key', client_secret='your_consumer_secret', resource_owner_key='your_access_token', resource_owner_secret='your_access_token_secret' ) # Make authenticated requests immediately response = session.get('https://api.example.com/protected_resource') ``` -------------------------------- ### Using Pre-existing OAuth 2.0 Access Tokens (Python) Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet demonstrates how to initialize an `OAuth2EnhancedSession` with an already obtained access token dictionary. This is useful for applications that persist tokens and need to re-establish an authenticated session without re-running the full authorization flow. ```python from requests_enhanced import OAuth2EnhancedSession token = { 'access_token': 'your_access_token', 'token_type': 'Bearer', 'expires_in': 3600, 'refresh_token': 'your_refresh_token' } session = OAuth2EnhancedSession( client_id='your_client_id', token=token ) # Make authenticated requests response = session.get('https://api.example.com/user') ``` -------------------------------- ### Checking and Formatting Code Style for requests-enhanced (Bash) Source: https://github.com/khollingworth/requests-enhanced/blob/main/README.md This snippet provides Bash commands for maintaining code style in the `requests-enhanced` project using `black` for formatting and `flake8` for linting. It shows how to apply formatting and check for style violations across source, test, and example files. ```bash # Format code black src tests examples # Check code style flake8 src tests examples ``` -------------------------------- ### Enabling HTTP/2 and HTTP/3 with requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/quick-reference.md Explains how to integrate HTTP/2 and HTTP/3 support into a `requests-enhanced` session using `HTTP2Adapter` and `HTTP3Adapter`. It demonstrates mounting these adapters to handle HTTPS requests, including an option for HTTP/3 to fallback to HTTP/2. ```python from requests_enhanced import HTTP2Adapter, HTTP3Adapter # HTTP/2 http2_adapter = HTTP2Adapter() session.mount("https://", http2_adapter) # HTTP/3 with fallback http3_adapter = HTTP3Adapter(fallback_to_http2=True) session.mount("https://", http3_adapter) ``` -------------------------------- ### Handling OAuth-Specific Errors with requests-enhanced in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet demonstrates robust error handling for OAuth operations, including checking for `OAuthNotAvailableError` if dependencies are missing and catching `TokenExpiredError` or `TokenRequestDenied` during requests. It shows how to gracefully manage common OAuth issues. Dependencies include `requests_enhanced`, `oauthlib.oauth2`, and `requests_oauthlib`. ```Python from requests_enhanced import OAuth1EnhancedSession, OAuth2EnhancedSession, OAuthNotAvailableError try: # Check if OAuth is available session = OAuth1EnhancedSession( client_key='key', client_secret='secret' ) except OAuthNotAvailableError: print("OAuth dependencies not installed. Run: pip install requests-enhanced[oauth]") # Handle OAuth-specific errors from oauthlib.oauth2 import TokenExpiredError from requests_oauthlib import TokenRequestDenied try: response = session.get('https://api.example.com/data') except TokenExpiredError: print("Token expired, need to refresh") except TokenRequestDenied as e: print(f"Token request denied: {e}") ``` -------------------------------- ### Configuring Custom Retries in requests-enhanced Session Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/usage_guide.md This snippet demonstrates how to configure custom retry logic for a `requests-enhanced` session using `requests.adapters.Retry`. It specifies the total number of retries, backoff factor, HTTP status codes to retry on, and allowed HTTP methods, applying these settings to all session requests. ```python from requests_enhanced import Session from requests.adapters import Retry # Custom retry configuration retry_config = Retry( total=5, # Total number of retries backoff_factor=0.5, # Backoff factor between retries status_forcelist=[500, 502, 503, 504], # Status codes to retry on allowed_methods=["GET", "POST"] # HTTP methods to retry ) # Create session with custom retry configuration session = Session(retry_config=retry_config) response = session.get("https://api.example.com/resources") ``` -------------------------------- ### Implementing OAuth2 Session Reuse with requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet demonstrates how to create an `APIClient` class that reuses an `OAuth2EnhancedSession` for making authenticated API requests. It includes methods for token persistence (`_save_token`, `_load_token`) and automatic token refresh, ensuring efficient and secure session management. ```Python from requests_enhanced import OAuth2EnhancedSession class APIClient: def __init__(self, client_id, client_secret): self.session = OAuth2EnhancedSession( client_id=client_id, auto_refresh_url='https://api.example.com/oauth/token', auto_refresh_kwargs={'client_secret': client_secret}, token_updater=self._save_token ) # Load existing token if available token = self._load_token() if token: self.session.token = token def _save_token(self, token): # Implement token persistence pass def _load_token(self): # Implement token loading pass def get_user_data(self): return self.session.get('https://api.example.com/user').json() def get_posts(self): return self.session.get('https://api.example.com/posts').json() ``` -------------------------------- ### Loading OAuth Secrets from Environment Variables in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet demonstrates the best practice of loading sensitive OAuth credentials like `client_id` and `client_secret` from environment variables using `os.getenv()`. This prevents hardcoding secrets directly in the code, enhancing security. Dependencies include `os` and `requests_enhanced`. ```Python import os from requests_enhanced import OAuth2EnhancedSession session = OAuth2EnhancedSession( client_id=os.getenv('OAUTH_CLIENT_ID'), client_secret=os.getenv('OAUTH_CLIENT_SECRET'), # Never hardcode secrets redirect_uri=os.getenv('OAUTH_REDIRECT_URI') ) ``` -------------------------------- ### Implementing Robust Request Retry and Token Refresh Logic in Python Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This function provides a robust mechanism for making authenticated requests, incorporating automatic token refresh on `TokenExpiredError` and exponential backoff with retries on other `RequestException` types. It ensures resilience against transient network issues and expired tokens. Dependencies include `requests_enhanced`, `requests.exceptions`, `oauthlib.oauth2`, and `time`. ```Python from requests_enhanced import OAuth2EnhancedSession from requests.exceptions import RequestException from oauthlib.oauth2 import TokenExpiredError import time def make_authenticated_request(session, url, max_retries=3): """Make request with automatic token refresh and retry logic""" for attempt in range(max_retries): try: response = session.get(url) response.raise_for_status() return response.json() except TokenExpiredError: # Token expired, refresh it session.refresh_token( 'https://api.example.com/oauth/token', client_secret=os.getenv('OAUTH_CLIENT_SECRET') ) continue except RequestException as e: if attempt == max_retries - 1: raise time.sleep(2 ** attempt) # Exponential backoff continue raise Exception("Max retries exceeded") ``` -------------------------------- ### Configuring OAuth2 for Google with requests-enhanced Source: https://github.com/khollingworth/requests-enhanced/blob/main/docs/oauth-usage-guide.md This snippet illustrates configuring `OAuth2EnhancedSession` for Google's OAuth 2.0. It demonstrates how to specify client ID, redirect URI, and scopes, along with additional parameters like `access_type='offline'` for refresh tokens and `prompt='consent'` during authorization. It also shows token exchange and subsequent API calls. ```Python from requests_enhanced import OAuth2EnhancedSession session = OAuth2EnhancedSession( client_id='your_google_client_id', redirect_uri='http://localhost:8080/callback', scope=['openid', 'email', 'profile'] ) # Authorization URL with additional parameters auth_url, state = session.authorization_url( 'https://accounts.google.com/o/oauth2/auth', access_type='offline', # For refresh tokens prompt='consent' ) # Token exchange token = session.fetch_token( 'https://oauth2.googleapis.com/token', authorization_response=callback_url, client_secret='your_google_client_secret' ) # API requests profile = session.get('https://www.googleapis.com/oauth2/v2/userinfo').json() ```