This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
# 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
|
||||
|
||||
```python
|
||||
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
|
||||
(default `False`). 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
|
||||
(default `600`).
|
||||
|
||||
## Behavior
|
||||
|
||||
- Requests without an `Origin` header pass through untouched.
|
||||
- Simple cross-origin requests with an allowed origin get
|
||||
`Access-Control-Allow-Origin` (plus `Access-Control-Allow-Credentials` and
|
||||
`Access-Control-Expose-Headers` when configured) added to the response.
|
||||
Headers already set by the handler are never overwritten.
|
||||
- Preflight requests (`OPTIONS` with `Origin` and
|
||||
`Access-Control-Request-Method` headers) are answered directly by the mixin
|
||||
with `200 OK` (or `400` with a `Disallowed 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-registered `OPTIONS` handlers 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.
|
||||
Reference in New Issue
Block a user