CorsMiddleware

Documentation for the `CorsMiddleware` class.

Namespace blazingapi.security.middleware

The CorsMiddleware class is a middleware component that is responsible for handling Cross-Origin Resource Sharing (CORS) in your application. It extends the BaseMiddleware class and modifies response headers based on specified settings.

Class Definition

from blazingapi.middleware import BaseMiddleware
from blazingapi.settings import settings


class CorsMiddleware(BaseMiddleware):

    def execute_after(self, request, response):

        origin = request.headers.get("Origin", "*")

        if "*" in settings.CORS_ALLOWED_ORIGINS or origin in settings.CORS_ALLOWED_ORIGINS:
            response.headers['Access-Control-Allow-Origin'] = origin if "*" not in settings.CORS_ALLOWED_ORIGINS else "*"
            response.headers['Access-Control-Allow-Methods'] = ",".join(settings.CORS_ALLOWED_METHODS)
            response.headers['Access-Control-Allow-Headers'] = ",".join(settings.CORS_ALLOWED_HEADERS)

        if request.method == "OPTIONS":
            response.status = 204
            response.body = ""

        return response