Skip to contentSaltar al contenido
125+ QA and SEO checks per page

CORS Handling Implementation in Python

11 min readbeginner
Website QA and SEO audits

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 is the browser's rule for when script running on origin A may read a response that came from origin B. The server never decides whether the request is sent; it decides whether the reply is readable, and it says so in response headers the browser enforces on the caller's behalf. Two request shapes exist. A simple request (GET, HEAD, or POST with a form-style Content-Type and only safelisted headers) goes straight out, and the browser hides the answer unless Access-Control-Allow-Origin matches. Anything else, a PATCH, an Authorization header, a Content-Type of application/json, triggers a preflight: a separate OPTIONS request carrying Access-Control-Request-Method and Access-Control-Request-Headers that must be answered with the right headers and no body before the real request is permitted to leave the machine. Three details cause most of the bugs. Allow-Origin holds a single value, so an allowlist means echoing the caller's Origin back, which makes the response depend on Origin and therefore requires Vary: Origin or a shared cache will hand one site's grant to another. Credentials, meaning cookies and TLS client certificates, are incompatible with the * wildcard and the browser rejects that combination outright. And any response header the client did not already know about stays invisible to the fetching code unless Access-Control-Expose-Headers names it. The eight languages here diverge on where that state machine lives. Five have a ready-made CORS component to configure, and they still disagree about what happens when it sits in the wrong place in the chain relative to authentication or error handling. Two hand you nothing but a header map and a method string and expect you to write the branch yourself. One puts the allowlist in the type system, where it is erased before a single request arrives. One of those two also runs the client half, and there CORS arrives not as a header on a wire but as a null where a value should have been.

CORS Handling in Python: what you actually reach for

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.

Python implementation

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__. Hold the allowlist as a set of bytes so no request needs decoding. The preflight branch must return without ever awaiting the inner application: handing an OPTIONS probe to a router that has no OPTIONS route is the line a reviewer circles, because the router will answer 405 and the browser will call that a CORS failure.
python
# 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 Free

The Python-specific trap

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.

Performance in Python, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port CORS Handling between languages.

Real-World Applications

CORS Handling is used extensively in production software: web frameworks, content management systems, API gateways, and SPA architectures implement this pattern for handling HTTP requests and rendering. In Python, check whether the standard library or a well maintained package already provides it before you write your own. Understanding CORS Handling helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

CORS Handling appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose CORS Handling over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of CORS Handling to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

If you are a student, see what Replit offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.