CORS Handling Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓CORS Handling runs in O(1) time and O(1) space, in Python as in every other language.
- ✓http.server and wsgiref stop one level below CORS: they expose send_header and know nothing about an origin.
- ✓A decorator stack cannot express this one. The ASGI signature is (scope, receive, send), and the response half exists only if you close over send and pass a replacement downward, so the policy takes the form of a class with an async __call__.
- ✓The Python trap: ASGI header lists are list[tuple[bytes, bytes]], not a mapping, and duplicate names are legal at that layer.
- ✓Preflight handling is a dict comprehension over a few header pairs plus one set lookup, which is microseconds and is dwarfed by the cost of one more ASGI frame.
What CORS Handling actually is
CORS Handling in Python: what you actually reach for
Python implementation
# Pure-ASGI CORS middleware: no dependency, runs under uvicorn, hypercorn or daphne.
# ASGI headers are a list of (bytes, bytes) pairs and duplicate names are legal, so the
# response path REPLACES Access-Control-Allow-Origin instead of appending a second one.
from typing import Any, Awaitable, Callable
Msg = dict[str, Any]
Send = Callable[[Msg], Awaitable[None]]
ALLOWED = {b"https://app.example.dev", b"https://ops.example.dev"}
EXPOSED = b"X-Request-Id, X-Rate-Limit-Remaining"
class CorsMiddleware:
def __init__(self, app: Any) -> None:
self.app = app
async def __call__(self, scope: Msg, receive: Any, send: Send) -> None:
if scope["type"] != "http":
return await self.app(scope, receive, send)
req = {k.lower(): v for k, v in scope["headers"]}
origin = req.get(b"origin")
ok = origin in ALLOWED
# A preflight is OPTIONS *and* Access-Control-Request-Method. Bare OPTIONS is not.
if scope["method"] == "OPTIONS" and b"access-control-request-method" in req:
out = [(b"vary", b"origin, access-control-request-headers")]
if ok:
out += [(b"access-control-allow-origin", origin),
(b"access-control-allow-credentials", b"true"),
(b"access-control-allow-methods", b"GET, POST, PATCH, DELETE"),
(b"access-control-allow-headers", req.get(b"access-control-request-headers", b"")),
(b"access-control-max-age", b"600")]
await send({"type": "http.response.start", "status": 204, "headers": out})
return await send({"type": "http.response.body", "body": b""})
async def wrapped(message: Msg) -> None:
if message["type"] == "http.response.start":
h = [p for p in message["headers"] if p[0].lower() != b"access-control-allow-origin"]
h.append((b"vary", b"origin"))
if ok:
h += [(b"access-control-allow-origin", origin),
(b"access-control-allow-credentials", b"true"),
(b"access-control-expose-headers", EXPOSED)]
message["headers"] = h
await send(message)
await self.app(scope, receive, wrapped)Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for CORS Handling?
http.server and wsgiref stop one level below CORS: they expose send_header and know nothing about an origin. Real deployments take the ASGI or WSGI seam instead. Starlette, and therefore FastAPI, exports CORSMiddleware from starlette.middleware.cors; Django uses the third-party django-cors-headers app; Flask uses the third-party flask-cors extension. All three wrap the same two hooks: read the pairs in scope['headers'] on the way in, and edit the header list carried on the http.response.start message on the way out. Nothing in CPython itself models a policy.
What is the most common Python mistake when implementing CORS Handling?
ASGI header lists are list[tuple[bytes, bytes]], not a mapping, and duplicate names are legal at that layer. Appending (b'access-control-allow-origin', origin) to a response whose handler already set that header emits the header twice, and a browser treats a multi-valued grant as invalid, so the network tab shows the header present while the read is blocked. Filter the list before you append. Its sibling is passing str where bytes are required, which raises inside the server's header encoder with a traceback that points at uvicorn rather than at your middleware.
How does CORS Handling actually perform in Python?
Preflight handling is a dict comprehension over a few header pairs plus one set lookup, which is microseconds and is dwarfed by the cost of one more ASGI frame. The charge that actually shows up is structural: every response now passes through an extra async closure, so there is one more coroutine object and one more await hop per message, and on a streaming endpoint messages arrive per chunk rather than per response. Access-Control-Max-Age is the lever that removes work instead of shrinking it, deleting a whole round trip from the client. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.