Skip to content

CORSConfig

CORS extends for Cross-Origin Resource Sharing and it is one of the built-in middlewares of Esmerald. When a CORSConfig object is passed to an application instance, it will automatically start the CORSMiddleware.

Tip

More information about CORS here.

Check

If the allowed_hosts is provided via application instance or settings, it will automatically start the TrustedHostMiddleware.

CORSConfig and application

To use the CORSConfig in an application instance.

from esmerald import CORSConfig, Esmerald

cors_config = CORSConfig(
    allow_origins=["https://example.com", "https://foobar.org"], allow_methods=["GET", "POST"]
)

app = Esmerald(cors_config=cors_config)

Another example

from esmerald import CORSConfig, Esmerald

cors_config = CORSConfig(
    allow_origins=["https://www.example.com", "https://foobar.org"],
    allow_methods=["GET", "POST"],
    allow_credentials=True,
)

app = Esmerald(cors_config=cors_config)

Parameters

All the parameters and defaults are available in the CORSConfig Reference.

CORSConfig and application settings

The CORSConfig can be done directly via application instantiation but also via settings.

from esmerald import CORSConfig, EsmeraldAPISettings


class CustomSettings(EsmeraldAPISettings):
    @property
    def cors_config(self) -> CORSConfig:
        """
        Initial Default configuration for the CORS.
        This can be overwritten in another setting or simply override
        `allow_origins` or then override the `def cors_config()`
        property to change the behavior of the whole cors_config.
        """
        if not self.allow_origins:
            return None
        return CORSConfig(allow_origins=self.allow_origins, allow_methods=["*"])

This will make sure you keep the settings clean, separated and without a bloated Esmerald instance.