CORS Middleware

class smarter.lib.django.middleware.cors.SmarterCorsMiddleware(get_response)[source]

Bases: CorsMiddleware, SmarterHelperMixin

Django 6 / ASGI-safe dynamic CORS middleware.

Design rules: - no shared request state on self - no coroutine guessing in core logic - single execution path (sync + async unified)

Middleware for handling Cross-Origin Resource Sharing (CORS) headers in the application.

This middleware extends the default CORS handling to dynamically add llm_client URLs to the allowed origins at runtime. It ensures that requests from valid llm_client origins are permitted by updating the CORS allowed origins list based on the current request context.

The middleware also provides additional logic to handle internal IP addresses, health check endpoints, and logging for debugging and auditing purposes.

Variables:
  • _url (Optional[SplitResult]) – The parsed URL (as a urllib.parse.SplitResult) for the current request, or None.

  • _llm_client (Optional[LLMClient]) – The llm_client instance associated with the current request, or None.

  • request (Optional[HttpRequest]) – The current Django HTTP request object, or None.

Key Features

  • Dynamically adds llm_client URLs to the CORS allowed origins list.

  • Handles requests from internal IP addresses and health check endpoints.

  • Provides detailed logging for CORS-related events and decisions.

  • Integrates with Django and the django-cors-headers package.

Note

  • The llm_client URL is only added to the allowed origins if an llm_client is associated with the request.

  • Internal requests and health checks are short-circuited for efficiency.

  • Logging is controlled via a waffle switch and the application’s log level.

Example

To enable this middleware, add it to your Django project’s middleware settings:

MIDDLEWARE = [
    ...
    'smarter.lib.django.middleware.cors.SmarterCorsMiddleware',
    ...
]
Parameters:

request (django.http.HttpRequest) – The incoming HTTP request object.

Returns:

The HTTP response object, potentially with CORS headers added.

Return type:

django.http.response.HttpResponseBase or Awaitable[HttpResponseBase]

__init__(get_response)[source]

Note: this needs to exist.

something in the Python MRO requires it, even if it does nothing. If you remove this, you will get a mysterious error about something downstream expecting exactly one object.

property formatted_class_name: str

Return the formatted class name for logging purposes.