ash-utils
Python library containing common utilities used across various ASH projects.
Features
- CatchUnexpectedExceptionsMiddleware - Global exception handler for unexpected errors
- RequestIDMiddleware - Request ID tracking for improved logging and tracing
- BaseApi - Base HTTP client with built-in error handling and request ID propagation
- configure_security_headers - Function provides a pre-configured security header setup for FastAPI applications following security best practices.
Installation
PyPi
pip install ashwelness-utils
# OR
poetry add ashwelness-utils
From github
In order to install Ash DAL directly from GitHub repository, run:
pip install git+https://github.com/meetash/ash-utils.git@main
# OR
poetry add git+https://github.com/meetash/ash-utils.git@main
Usage
- CatchUnexpectedExceptionsMiddleware
Purpose: Catch all unexpected exceptions and return a standardized error response.
from fastapi import FastAPI
from ash_utils.middlewares import CatchUnexpectedExceptionsMiddleware
app = FastAPI()
# Add middleware with custom error message
app.add_middleware(
CatchUnexpectedExceptionsMiddleware,
response_error_message="Internal server error",
response_status_code=500
)
@app.get("/")
async def root():
# This exception will be caught by the middleware
raise ValueError("Something went wrong")
- RequestIDMiddleware
Purpose: Add request ID tracking to headers and logs for better request correlation.
from fastapi import FastAPI
from ash_utils.middlewares import RequestIDMiddleware
app = FastAPI()
# Add middleware with default header name (X-Request-ID)
app.add_middleware(RequestIDMiddleware)
@app.get("/")
async def root():
return {"message": "Hello World"}
Example Request/Response:
GET / HTTP/1.1
Host: localhost:8000
X-Request-ID: 123e4567-e89b-12d3-a456-426614174000
HTTP/1.1 200 OK
X-Request-ID: 123e4567-e89b-12d3-a456-426614174000
- BaseApi (HTTP Client)
Purpose: Make HTTP requests with automatic error handling and request ID propagation.
from http import HTTPMethod
from urllib.parse import urljoin
from ash_utils.apis.base_api import BaseApi
from httpx import AsyncClient
from py_cachify import cached
import constants
from domain.entities.common import PartnerConfigEntity
class ClientManagementServiceApi(BaseApi):
PARTNER_PATH = "/api/v1/partners/{partner_id}"
def __init__(self, url: str, api_key: str, client: AsyncClient):
self.token = api_key
self.base_url = url
self.headers = {"x-api-key": api_key}
super().__init__(client=client)
@cached(key=constants.PARTNER_CONFIG_CACHE_KEY, ttl=constants.PARTNER_CONFIG_CACHE_TTL)
async def get_partner_config(self, partner_id: str) -> PartnerConfigEntity:
url = urljoin(self.base_url, self.PARTNER_PATH.format(partner_id=partner_id))
response = await self._send_request(
method=HTTPMethod.GET,
url=url,
headers=self.headers,
)
response_data = response.json()
return PartnerConfigEntity(**response_data)
- Security Headers Configuration
Purpose: This function provides a pre-configured security header setup for FastAPI applications following security best practices.
from fastapi import FastAPI
from ash_utils.middlewares import configure_security_headers
app = FastAPI()
configure_security_headers(app)
@app.get("/")
async def root():
return {"message": "Hello Secure World!"}
The configure_security_headers function adds these security middlewares with safe defaults:
- Content Security Policy (CSP)
- X-Content-Type-Options
- Referrer-Policy
- X-Frame-Options
- HTTP Strict Transport Security (HSTS)
- Permissions-Policy
Configuration
Middleware Configuration Options:
- CatchUnexpectedExceptionsMiddleware
response_error_message: Error message to return to clientsresponse_status_code: HTTP status code to return (default: 500)
- RequestIDMiddleware
header_name: Custom header name for request ID (default: X-Request-ID)
- BaseApi Configuration
request_id_header_name: Header name for request ID propagation (default: X-Request-ID)
Error Handling
The BaseApi class provides two custom exceptions:
ThirdPartyRequestError: For network-level errorsThirdPartyHttpStatusError: For HTTP 4xx/5xx responses
Best Practices
- Add CatchUnexpectedExceptionsMiddleware first in the middleware chain
- Configure a meaningful error message for production environments
- Use the BaseApi for all external API calls to ensure consistent error handling
Metadata
Release files for ashwelness-utils 0.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| ashwelness_utils-0.1.1.tar.gz | 26.9 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| ashwelness_utils-0.1.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 35.1 kB
Release files / ashwelness_utils-0.1.1.tar.gz
| Download URL | ashwelness_utils-0.1.1.tar.gz |
|---|---|
| Size | 26.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
2dc8e2a3c3b9082beba7f085cc8e4754dad43485a75c2155131d9a930d25bae7
|
|
BLAKE2b-256 checksum How to use checksums |
e090b4042361534cb227861ce8d7907764758c561ebd11ac39f28ee64cac3ae2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.5.29
|
Release files / ashwelness_utils-0.1.1-py3-none-any.whl
| Download URL | ashwelness_utils-0.1.1-py3-none-any.whl |
|---|---|
| Size | 8.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a59cc4d82f80f881d9a9ce1a030e1be28d0f7b23966eae716d4cdd6eaa8e8b0f
|
|
BLAKE2b-256 checksum How to use checksums |
4872d7effa78fabc0ecb8e6e7ddd61ee7924303eedc5938d0ff9c2ff9ebbcaa5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.5.29
|