birchrest.middlewares package

Submodules

birchrest.middlewares.cors module

class birchrest.middlewares.cors.Cors(allow_origins: List[str] = ['*'], allow_methods: List[str] = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'], allow_headers: List[str] = ['Content-Type', 'Authorization'], allow_credentials: bool = False, max_age: int = 86400)[source]

Bases: Middleware

Middleware for handling Cross-Origin Resource Sharing (CORS) in HTTP requests.

This middleware ensures that the server can respond to cross-origin requests by controlling which origins, methods, and headers are allowed. It also handles preflight requests (OPTIONS method) for HTTP requests that require complex CORS handling, such as when using methods other than GET or POST or custom headers.

The CORS settings, such as allowed origins, methods, and headers, can be configured when initializing the middleware. By default, it allows all origins, commonly used methods, and a few standard headers.

Attributes:

allow_origins (List[str]): List of allowed origins. Defaults to [“*”], allowing all origins. allow_methods (List[str]): List of allowed HTTP methods. Defaults to common methods like GET, POST, PUT, DELETE, etc. allow_headers (List[str]): List of allowed request headers. Defaults to [“Content-Type”, “Authorization”]. allow_credentials (bool): Whether or not to allow credentials (cookies, HTTP authentication, etc.). Defaults to False. max_age (int): How long the results of a preflight request can be cached (in seconds). Defaults to 86400 seconds (24 hours).

Methods:

__call__(req, res, next): Main entry point for the middleware. Adds the appropriate CORS headers to the response based on the request. _handle_preflight(origin, res): Handles preflight (OPTIONS) requests by responding with the appropriate CORS headers. _add_cors_headers(origin, res): Adds CORS headers to the response for non-OPTIONS requests. _is_origin_allowed(origin): Checks if the origin is allowed based on the allow_origins setting.

birchrest.middlewares.logger module

class birchrest.middlewares.logger.Logger[source]

Bases: Middleware

Middleware to log incoming requests and outgoing responses with enhanced formatting and colors. Logs useful information including request method, path, client address, correlation ID, response status, and time taken.

birchrest.middlewares.rate_limiter module

class birchrest.middlewares.rate_limiter.RateLimiter(max_requests: int = 2, window_seconds: int = 10)[source]

Bases: Middleware

A rate-limiting middleware that limits the number of requests per client (IP or token) within a specified time window.

Module contents

This module provides built-in middlewares for the BirchRest framework, as well as the base class for creating custom user-defined middlewares.

Middlewares are used to process requests and responses, either globally or for specific routes. They are executed in the order they are registered and can perform tasks such as logging, handling CORS, rate-limiting, and more.

Built-in middlewares: - RateLimiter: Limits the number of requests from a single client over a period of time. - Logger: Logs incoming requests and outgoing responses, providing useful insights for debugging and monitoring. - Cors: Handles Cross-Origin Resource Sharing (CORS) headers to manage access from different domains.

Custom middlewares: - Middleware: This is the base class that users should inherit from to create their own middleware.

Custom middlewares should implement the __call__ method to define their specific behavior. Both synchronous and asynchronous middlewares are supported.

To use a middleware: 1. Built-in middlewares can be registered directly to a BirchRest application instance. 2. For custom middlewares, inherit from the Middleware class and implement the call method.

Example of a user-defined middleware:

```python from birchrest.middleware import Middleware

class CustomMiddleware(Middleware):
async def __call__(self, req, res, next):

# Custom processing logic before handling the request print(f”Processing request {req.method} {req.path}”) await next() # Continue to the next middleware or route handler # Custom logic after handling the request print(f”Response sent with status {res.status_code}”)

class birchrest.middlewares.Cors(allow_origins: List[str] = ['*'], allow_methods: List[str] = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'], allow_headers: List[str] = ['Content-Type', 'Authorization'], allow_credentials: bool = False, max_age: int = 86400)[source]

Bases: Middleware

Middleware for handling Cross-Origin Resource Sharing (CORS) in HTTP requests.

This middleware ensures that the server can respond to cross-origin requests by controlling which origins, methods, and headers are allowed. It also handles preflight requests (OPTIONS method) for HTTP requests that require complex CORS handling, such as when using methods other than GET or POST or custom headers.

The CORS settings, such as allowed origins, methods, and headers, can be configured when initializing the middleware. By default, it allows all origins, commonly used methods, and a few standard headers.

Attributes:

allow_origins (List[str]): List of allowed origins. Defaults to [“*”], allowing all origins. allow_methods (List[str]): List of allowed HTTP methods. Defaults to common methods like GET, POST, PUT, DELETE, etc. allow_headers (List[str]): List of allowed request headers. Defaults to [“Content-Type”, “Authorization”]. allow_credentials (bool): Whether or not to allow credentials (cookies, HTTP authentication, etc.). Defaults to False. max_age (int): How long the results of a preflight request can be cached (in seconds). Defaults to 86400 seconds (24 hours).

Methods:

__call__(req, res, next): Main entry point for the middleware. Adds the appropriate CORS headers to the response based on the request. _handle_preflight(origin, res): Handles preflight (OPTIONS) requests by responding with the appropriate CORS headers. _add_cors_headers(origin, res): Adds CORS headers to the response for non-OPTIONS requests. _is_origin_allowed(origin): Checks if the origin is allowed based on the allow_origins setting.

class birchrest.middlewares.Logger[source]

Bases: Middleware

Middleware to log incoming requests and outgoing responses with enhanced formatting and colors. Logs useful information including request method, path, client address, correlation ID, response status, and time taken.

class birchrest.middlewares.Middleware[source]

Bases: ABC

Base class for all middlewares. All middlewares should inherit from this class. This class provides a unified interface to handle both synchronous and asynchronous middlewares.

class birchrest.middlewares.RateLimiter(max_requests: int = 2, window_seconds: int = 10)[source]

Bases: Middleware

A rate-limiting middleware that limits the number of requests per client (IP or token) within a specified time window.