Skip to content

Instantly share code, notes, and snippets.

@FND
Last active December 14, 2022 06:48
Show Gist options
  • Save FND/204ba41bf6ae485965ef to your computer and use it in GitHub Desktop.
Save FND/204ba41bf6ae485965ef to your computer and use it in GitHub Desktop.
CORS-enabled WSGI server (minimal sample)
#!/usr/bin/env python
def handler(environ, start_response):
method = environ["REQUEST_METHOD"]
origin = environ.get("HTTP_ORIGIN")
cookie = environ.get("HTTP_COOKIE", "N/A")
print ""
print method, environ["PATH_INFO"]
print "Origin:", origin
print "Cookie:", cookie
cors = origin
preflight = cors and method == "OPTIONS"
headers = [("Content-Type", "text/plain")]
if cors:
headers.extend([
("Access-Control-Allow-Origin", origin),
("Access-Control-Allow-Credentials", "true")
])
if preflight:
headers.extend([
("Access-Control-Allow-Methods", "POST"),
("Access-Control-Allow-Headers", "Content-Type")
])
else:
headers.append(("Set-Cookie", "auth=fnd"))
if method == "OPTIONS":
start_response("204 No Content", headers)
return []
else:
start_response("200 OK", headers)
return ["Cookie: ", cookie]
if __name__ == "__main__":
import sys
from wsgiref.simple_server import make_server
port = sys.argv[1]
srv = make_server("localhost", int(port), handler)
srv.serve_forever()
@grantcurell
Copy link

I don't even know how I ended up Googling this, but you are the best for posting this. Saved me so much time figuring out all the syntax. I knew what I wanted, but I had no clue what the right syntax was.

@FND
Copy link
Author

FND commented Apr 30, 2020

Hey @grantcurell, I'm glad you found this and it proved useful - thanks for letting me know! (I don't even remember creating this... )

@StephenLeafWW
Copy link

This is pretty useful; was wondering how we do that with WGSI

@TautvydasDerzinskas
Copy link

This is pretty useful; was wondering how we do that with WGSI

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment