2.4 KiB
2.4 KiB
kaya-cors
CORS (Cross-Origin Resource Sharing) support for the Kaya web framework.
Provides CorsMixin, a KayaMixin that adds CORS response headers to outgoing
responses and answers CORS preflight (OPTIONS) requests, with the same
configuration parameters and semantics as FastAPI/Starlette's CORSMiddleware.
Usage
from kaya.core import KayaApp, HttpContext
from kaya.cors import CorsMixin
app = KayaApp(mixins=[
CorsMixin(
allow_origins=['https://example.com'],
allow_methods=('GET', 'POST'),
allow_headers=('X-Custom-Header',),
allow_credentials=True,
max_age=600,
)
])
@app.GET('/')
async def home(ctx: HttpContext):
await ctx.send_str(200, 'Hello World!')
Parameters
allow_origins: list of origins allowed to make cross-origin requests. Use['*']to allow any origin.allow_origin_regex: optional regex string matched (fullmatch) against the request origin.allow_methods: HTTP methods allowed for cross-origin requests (default('GET',)); use'*'to allow all standard methods.allow_headers: request headers allowed in cross-origin requests (default()); use'*'to mirror back any requested headers.allow_credentials: allow cookies/credentials in cross-origin requests (defaultFalse). When enabled, the allowed origin is always echoed explicitly instead of'*'.expose_headers: response headers made accessible to the browser.max_age: seconds browsers may cache the preflight response (default600).
Behavior
- Requests without an
Originheader pass through untouched. - Simple cross-origin requests with an allowed origin get
Access-Control-Allow-Origin(plusAccess-Control-Allow-CredentialsandAccess-Control-Expose-Headerswhen configured) added to the response. Headers already set by the handler are never overwritten. - Preflight requests (
OPTIONSwithOriginandAccess-Control-Request-Methodheaders) are answered directly by the mixin with200 OK(or400with aDisallowed CORS ...body when the origin, method or headers are not allowed). The preflight response is the only one delivered to the client: if the routing tree matches the request anyway (including user-registeredOPTIONShandlers or the 404 fallback), its output is discarded.
CorsMixin is a KayaMixin, so the app stays a KayaApp and both ASGI and
RSGI keep working.