Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+297 -200
View File
@@ -1,255 +1,352 @@
---
description: This rule provides comprehensive best practices for using the httpx library, covering code organization, performance, security, testing, and common pitfalls. Adhering to these guidelines will improve code quality, maintainability, and security when working with httpx.
globs: *.py
description: This guide outlines definitive best practices for using httpx, Python's modern HTTP client, ensuring robust, performant, and maintainable network interactions in both synchronous and asynchronous applications.
globs: **/*.py
---
# httpx Best Practices
This document outlines recommended practices for using the `httpx` library in Python. Following these guidelines will help ensure maintainable, performant, and secure code.
`httpx` is the de-facto modern HTTP client for Python, offering both synchronous and asynchronous APIs, native HTTP/2 support, and advanced features essential for high-throughput services. Adhere to these guidelines for optimal performance, reliability, and code clarity.
## Library Information:
## Code Organization and Structure
- Name: httpx
- Tags: web, python, http-client, async
### Always use a `Client` or `AsyncClient` instance
## 1. Code Organization and Structure
Avoid top-level helper functions (`httpx.get`, `httpx.post`) for anything beyond simple, one-off scripts. Client instances enable connection pooling, HTTP/2, and persistent configuration.
### 1.1 Directory Structure Best Practices
- **Dedicated Modules:** Organize httpx-related code into dedicated modules or packages.
- **Configuration:** Separate configuration settings (timeouts, headers, proxies) from the core logic.
- **Data Models:** Define data models (e.g., using `dataclasses` or `pydantic`) to represent request and response data.
Example:
my_project/
├── httpx_client/
│ ├── __init__.py
│ ├── client.py # httpx client setup, session management
│ ├── utils.py # Utility functions for request/response handling
│ ├── models.py # Data models for requests and responses
│ └── exceptions.py # Custom exceptions
├── ...
### 1.2 File Naming Conventions
- Use descriptive names that reflect the file's purpose (e.g., `api_client.py`, `request_utils.py`).
- Follow PEP 8 conventions (snake_case).
### 1.3 Module Organization
- **Layered Architecture:** Consider a layered architecture with modules for:
- **Client Initialization:** Handles httpx client setup (connection pooling, timeouts).
- **Request Building:** Constructs httpx Request objects.
- **Response Handling:** Parses and validates responses, handles errors.
- **Abstraction:** Abstract away direct httpx calls behind service functions or classes.
### 1.4 Component Architecture
- **Reusable Components:** Design reusable components for common tasks like:
- **Authentication:** Implementing custom authentication flows.
- **Rate Limiting:** Managing API rate limits.
- **Retry Logic:** Handling transient errors with retry mechanisms.
### 1.5 Code Splitting Strategies
- **Feature-Based Splitting:** Split code based on features or API endpoints.
- **Abstraction:** Use interfaces or abstract base classes for httpx clients to facilitate mocking and testing.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
- **Factory Pattern:** Use a factory function or class to create httpx clients with different configurations.
- **Strategy Pattern:** Implement different request strategies based on the API requirements.
### 2.2 Recommended Approaches for Common Tasks
- **Client Instance Usage:** Always use `httpx.Client()` or `httpx.AsyncClient()` for making requests. This enables connection pooling.
- **Context Managers:** Use the client as a context manager (`with httpx.Client() as client:`) or explicitly close the connection pool (`client.close()`).
- **Timeouts:** Always set timeouts to prevent hanging requests.
- **Error Handling:** Use `try-except` blocks to handle `HTTPStatusError` and `RequestError`.
- **Async Support:** Utilize `httpx.AsyncClient()` for concurrent requests.
- **Configuration Sharing:** Configure default headers, parameters, and authentication at the client level.
python
❌ BAD:
```python
import httpx
with httpx.Client(timeout=10.0, headers={'User-Agent': 'MyApp/1.0'}) as client:
try:
response = client.get('https://example.com/api/data')
response.raise_for_status() # Raise HTTPStatusError for bad responses (4xx or 5xx)
data = response.json()
# Process data
except httpx.HTTPStatusError as e:
print(f"HTTP Error: {e}")
except httpx.RequestError as e:
print(f"Request Error: {e}")
# In a loop or repeated calls, this creates new connections every time
for _ in range(5):
response = httpx.get("https://api.example.com/data")
# ... process response
```
✅ GOOD:
```python
import httpx
### 2.3 Anti-patterns and Code Smells
# Client is instantiated once and reused
with httpx.Client() as client:
for _ in range(5):
response = client.get("https://api.example.com/data")
# ... process response
```
- **Global Client Instances:** Avoid creating global httpx client instances without proper management of their lifecycle.
- **Ignoring Errors:** Never ignore exceptions raised by httpx. Always handle them appropriately.
- **Hardcoding URLs:** Avoid hardcoding URLs directly in the code. Use configuration files or environment variables.
### Instantiate a single client per process or request scope
### 2.4 State Management
Reuse `Client`/`AsyncClient` instances. Creating new clients in a hot loop defeats connection pooling and can exhaust resources. Pass a scoped client or use a global instance (with caution in async apps).
- **Statelessness:** Design components to be as stateless as possible.
- **Dependency Injection:** Use dependency injection to provide httpx clients to components that need them.
❌ BAD:
```python
# In an async web handler, this creates a new client per request
async def get_user_data(user_id: str):
async with httpx.AsyncClient() as client: # Client created per request
response = await client.get(f"https://api.example.com/users/{user_id}")
return response.json()
```
### 2.5 Error Handling Patterns
✅ GOOD:
```python
# Instantiate client once at application startup
# For web frameworks, use dependency injection or app-level state
import httpx
- **Custom Exceptions:** Define custom exception classes to represent specific httpx-related errors.
- **Logging:** Log errors and warnings with sufficient context.
- **Retry Logic:** Implement retry logic for transient errors.
# Global client (careful with stateful clients in multi-tenant apps)
# For web frameworks like FastAPI, prefer dependency injection.
_async_client: httpx.AsyncClient | None = None
## 3. Performance Considerations
async def get_async_client() -> httpx.AsyncClient:
global _async_client
if _async_client is None:
_async_client = httpx.AsyncClient(base_url="https://api.example.com")
return _async_client
### 3.1 Optimization Techniques
async def get_user_data(user_id: str):
client = await get_async_client() # Reuse the same client
response = await client.get(f"/users/{user_id}")
return response.json()
```
- **Connection Pooling:** httpx automatically uses connection pooling when using `httpx.Client()` or `httpx.AsyncClient()`. Ensure you are leveraging this by reusing client instances.
- **HTTP/2:** Enable HTTP/2 support if the server supports it.
- **Keep-Alive:** Ensure keep-alive connections are enabled.
- **Asynchronous Operations:** Use `httpx.AsyncClient()` for concurrent I/O-bound operations.
### Use context managers for client lifecycle
### 3.2 Memory Management
Always use `with httpx.Client() as client:` or `async with httpx.AsyncClient() as client:` to guarantee proper shutdown of background workers and sockets.
- **Streaming Responses:** Use response streaming (`response.iter_bytes()`, `response.iter_text()`) for large responses to avoid loading the entire response into memory.
- **Chunked Uploads:** Use chunked uploads for large file uploads.
❌ BAD:
```python
client = httpx.Client()
response = client.get("https://api.example.com/data")
# client.close() might be forgotten, leading to resource leaks
```
### 3.3 Bundle Size Optimization
✅ GOOD:
```python
with httpx.Client() as client:
response = client.get("https://api.example.com/data")
# Client is automatically closed on exit
```
- **Tree Shaking:** Ensure your build tools perform tree shaking to remove unused httpx code.
## Common Patterns and Anti-patterns
### 3.4 Lazy Loading
### Prioritize `AsyncClient` in async contexts
- **On-Demand Initialization:** Initialize httpx clients only when they are needed.
In async web frameworks (FastAPI, Starlette, Quart) or any `asyncio`/`trio` application, use `AsyncClient` and `await client.get(...)` to keep the event loop free.
## 4. Security Best Practices
❌ BAD:
```python
# In an async function, using a synchronous client blocks the event loop
import httpx
import asyncio
### 4.1 Common Vulnerabilities and Prevention
async def fetch_sync_in_async():
client = httpx.Client() # This is a synchronous client
response = client.get("https://slow.example.com") # BLOCKS
client.close()
return response.text
```
- **Injection Attacks:** Sanitize user inputs to prevent injection attacks.
- **Man-in-the-Middle Attacks:** Always use HTTPS and verify SSL certificates.
- **Sensitive Data Exposure:** Avoid logging sensitive data (API keys, passwords).
✅ GOOD:
```python
import httpx
import asyncio
### 4.2 Input Validation
async def fetch_async():
async with httpx.AsyncClient() as client:
response = await client.get("https://fast.example.com") # Non-blocking
return response.text
```
- **Validate Request Data:** Validate all data before sending it to the API.
- **Validate Response Data:** Validate responses from the API.
### Stream large payloads to reduce memory pressure
### 4.3 Authentication and Authorization
For large files or responses, use `client.stream(...)` and iterate over `response.aiter_bytes()` (or `response.iter_bytes()` in sync mode) to process data as it arrives.
- **Secure Authentication:** Use secure authentication mechanisms (OAuth 2.0, JWT).
- **Least Privilege:** Grant only the necessary permissions to users.
❌ BAD:
```python
# Loads entire response into memory
response = client.get("https://large-file.example.com/data.zip")
file_content = response.content
# Process file_content
```
### 4.4 Data Protection
✅ GOOD:
```python
async with client.stream("GET", "https://large-file.example.com/data.zip") as response:
response.raise_for_status()
async for chunk in response.aiter_bytes():
# Process chunk as it arrives
pass
```
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Data Masking:** Mask sensitive data in logs and error messages.
### Configure client-level defaults for DRY code
### 4.5 Secure API Communication
Pass `auth`, `headers`, `params`, and `base_url` to the client constructor to apply them to all requests made by that client instance.
- **HTTPS:** Always use HTTPS.
- **TLS 1.3:** Use TLS 1.3 or higher.
- **Certificate Pinning:** Consider certificate pinning for added security (advanced).
❌ BAD:
```python
# Repeating headers and auth for every request
client.get("https://api.example.com/users", headers={"Authorization": "Bearer token"})
client.post("https://api.example.com/items", headers={"Authorization": "Bearer token"}, json={...})
```
## 5. Testing Approaches
✅ GOOD:
```python
client = httpx.Client(
base_url="https://api.example.com",
headers={"Authorization": "Bearer token"},
auth=httpx.BasicAuth("user", "pass") # Can also set auth here
)
client.get("/users")
client.post("/items", json={...})
```
### 5.1 Unit Testing
## Performance Considerations
- **Mocking:** Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to mock httpx calls.
- **Isolate Components:** Isolate components that use httpx for unit testing.
### Enable HTTP/2 explicitly
### 5.2 Integration Testing
For modern services, enable HTTP/2 support for multiplexing and improved performance. Install `httpx[http2]`.
- **Test Against Real APIs:** Perform integration tests against real APIs (with appropriate mocking or stubbing).
❌ BAD:
```python
client = httpx.Client() # Defaults to HTTP/1.1
```
### 5.3 End-to-End Testing
✅ GOOD:
```python
client = httpx.Client(http2=True) # Enables HTTP/2
```
- **Simulate User Flows:** Simulate end-to-end user flows that involve httpx calls.
### Set explicit, granular timeouts
### 5.4 Test Organization
Always configure timeouts. The default 5-second timeout is a safeguard, but customize it per-endpoint or client for specific needs (e.g., longer read timeouts for large responses).
- **Separate Test Files:** Create separate test files for each module or component.
❌ BAD:
```python
response = client.get("https://api.example.com/slow-endpoint") # Uses default 5s timeout
```
### 5.5 Mocking and Stubbing Techniques
✅ GOOD:
```python
# Client-level timeout
client = httpx.Client(timeout=httpx.Timeout(10.0, connect=5.0, read=30.0))
response = client.get("https://api.example.com/slow-endpoint")
- **Mock Responses:** Mock httpx responses to simulate different API scenarios.
- **Patch httpx Functions:** Patch httpx functions to control their behavior during tests.
- **RESPX:** Use RESPX for advanced mocking of httpx requests and responses.
# Request-level override
response = client.get("https://api.example.com/another-endpoint", timeout=5.0)
```
python
### Control redirects explicitly
`httpx` disables redirects by default. Only enable `follow_redirects=True` when necessary to avoid unexpected behavior or performance overhead.
❌ BAD:
```python
# Assuming redirects are handled automatically (they are not by default)
response = client.get("https://example.com/old-path")
print(response.url) # Might still be the old URL if not redirected
```
✅ GOOD:
```python
response = client.get("https://example.com/old-path", follow_redirects=True)
print(response.url) # Will be the new URL after redirect
```
## Common Pitfalls and Gotchas
### Handle HTTP errors gracefully
Always check for non-2xx responses. Use `response.raise_for_status()` to automatically raise `httpx.HTTPStatusError` for bad responses, or catch specific `httpx.HTTPError` subclasses.
❌ BAD:
```python
response = client.get("https://api.example.com/non-existent")
# Code proceeds even if status_code is 404 or 500
if response.status_code == 200:
data = response.json()
else:
print("Request failed") # Generic error handling
```
✅ GOOD:
```python
import httpx
try:
response = client.get("https://api.example.com/non-existent")
response.raise_for_status() # Raises HTTPStatusError for 4xx/5xx responses
data = response.json()
except httpx.HTTPStatusError as e:
print(f"HTTP error occurred: {e.response.status_code} - {e.response.text}")
except httpx.RequestError as e:
print(f"An error occurred while requesting {e.request.url!r}: {e}")
```
### Understand `response.url` is a URL object
`response.url` is an `httpx.URL` object, not a string. Access its components or convert to string explicitly.
❌ BAD:
```python
response = client.get("https://example.com/path?query=1")
if response.url == "https://example.com/path?query=1": # String comparison fails
pass
```
✅ GOOD:
```python
from httpx import URL
response = client.get("https://example.com/path?query=1")
if response.url == URL("https://example.com/path?query=1"): # Compare with URL object
pass
if str(response.url) == "https://example.com/path?query=1": # Explicit string conversion
pass
print(response.url.host) # Access components
```
## Type Hints
### Annotate `httpx` types for clarity and static analysis
Use `httpx.Client`, `httpx.AsyncClient`, `httpx.Response`, and `httpx.Request` for type hinting. This improves IDE support and aligns with modern Python practices.
❌ BAD:
```python
def fetch_data(client, url):
response = client.get(url)
return response.json()
```
✅ GOOD:
```python
import httpx
from typing import Dict, Any
def fetch_data(client: httpx.Client, url: str) -> Dict[str, Any]:
response: httpx.Response = client.get(url)
response.raise_for_status()
return response.json()
```
## Virtual Environments, Packaging, and Testing
### Always use virtual environments
This is standard Python practice. Ensure `httpx` and its optional dependencies (e.g., `httpx[http2,brotli]`) are installed in a dedicated virtual environment.
```bash
python -m venv .venv
source .venv/bin/activate
pip install "httpx[http2,brotli]"
```
### Declare `httpx` and extras in `pyproject.toml` or `requirements.txt`
For reproducible builds, explicitly list `httpx` and any required extras in your project's dependency management file.
`pyproject.toml`:
```toml
[project]
dependencies = [
"httpx[http2,brotli]",
]
```
`requirements.txt`:
```
httpx[http2,brotli]
```
### Use `pytest-httpx` for robust testing
For unit and integration tests, `pytest-httpx` provides excellent fixtures for mocking `httpx` requests, allowing you to simulate API responses without making actual network calls. For testing internal ASGI applications, `httpx.ASGITransport` is the correct tool.
✅ GOOD (using `pytest-httpx`):
```python
import httpx
import pytest
import respx
@respx.mock
async def test_get_data():
respx.get("https://example.com/api/data").mock(return_value=httpx.Response(200, json={"key": "value"}))
async with httpx.AsyncClient() as client:
response = await client.get("https://example.com/api/data")
# Install: pip install pytest-httpx
def test_fetch_user_data(httpx_mock):
httpx_mock.add_response(url="https://api.example.com/users/1", json={"id": 1, "name": "Test User"})
with httpx.Client() as client:
response = client.get("https://api.example.com/users/1")
assert response.status_code == 200
assert response.json() == {"key": "value"}
assert response.json() == {"id": 1, "name": "Test User"}
```
✅ GOOD (using `ASGITransport` for internal ASGI app):
```python
import httpx
from httpx import ASGITransport
from my_app import app # Assuming 'app' is your ASGI application
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
- **Forgetting to Close Clients:** Always close httpx clients to release resources.
- **Ignoring Timeouts:** Not setting timeouts can lead to hanging requests.
- **Incorrect Error Handling:** Improper error handling can mask critical errors.
- **Misunderstanding Connection Pooling:** Not reusing client instances negates connection pooling benefits.
- **Not Handling Asynchronous Context Correctly**: Using `await` improperly when using `AsyncClient()`.
### 6.2 Edge Cases
- **Character Encoding Issues:** Handle character encoding issues when processing text responses.
- **SSL Certificate Errors:** Handle SSL certificate errors gracefully.
- **Network Connectivity Issues:** Implement robust error handling for network connectivity issues.
### 6.3 Version-Specific Issues
- **Consult httpx Documentation:** Refer to the httpx documentation for version-specific issues and compatibility notes.
### 6.4 Compatibility Concerns
- **Asynchronous Libraries:** Ensure compatibility with other asynchronous libraries (e.g., asyncio).
- **Third-Party Packages:** Be aware of compatibility issues with third-party packages that use httpx.
### 6.5 Debugging Strategies
- **Logging:** Use logging to trace httpx requests and responses.
- **Debugging Tools:** Use debugging tools (e.g., pdb, ipdb) to inspect httpx code.
- **Wireshark/tcpdump:** Use network analysis tools (Wireshark, tcpdump) to capture and analyze network traffic.
## 7. Tooling and Environment
### 7.1 Recommended Tools
- **Development Environment:** Use a modern IDE (e.g., VS Code, PyCharm).
- **Dependency Management:** Use a dependency management tool (e.g., pipenv, poetry).
- **Testing Framework:** Use a testing framework (e.g., pytest, unittest).
- **Mocking Libraries:** Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`, RESPX).
### 7.2 Build Configuration
- **Reproducible Builds:** Ensure reproducible builds using dependency locking.
### 7.3 Linting and Formatting
- **PEP 8 Compliance:** Use a linter (e.g., flake8, pylint) to enforce PEP 8 compliance.
- **Code Formatting:** Use a code formatter (e.g., black, autopep8) to automatically format code.
### 7.4 Deployment
- **Containerization:** Use containerization (e.g., Docker) to ensure consistent deployments.
- **Environment Variables:** Configure httpx clients using environment variables.
### 7.5 CI/CD Integration
- **Automated Testing:** Integrate automated testing into your CI/CD pipeline.
- **Code Analysis:** Integrate code analysis tools into your CI/CD pipeline.
def test_my_asgi_app():
transport = ASGITransport(app=app)
with httpx.Client(transport=transport, base_url="http://test") as client:
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
```