Last active
December 14, 2022 06:48
-
-
Save FND/204ba41bf6ae485965ef to your computer and use it in GitHub Desktop.
CORS-enabled WSGI server (minimal sample)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
Hey @grantcurell, I'm glad you found this and it proved useful - thanks for letting me know! (I don't even remember creating this... )
This is pretty useful; was wondering how we do that with WGSI
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
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.