Last active
September 21, 2023 02:24
-
-
Save khalidx/6d6ebcd66b6775dae41477cffaa601e5 to your computer and use it in GitHub Desktop.
Python SimpleHTTPServer with CORS, supporting both Python 2 and 3
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 | |
# Usage: python simple_http_server_cors.py <port> | |
try: | |
# try to use Python 3 | |
from http.server import HTTPServer, SimpleHTTPRequestHandler, test as test_orig | |
import sys | |
def test (*args): | |
test_orig(*args, port=int(sys.argv[1]) if len(sys.argv) > 1 else 8000) | |
except ImportError: # fall back to Python 2 | |
from BaseHTTPServer import HTTPServer, test | |
from SimpleHTTPServer import SimpleHTTPRequestHandler | |
class CORSRequestHandler (SimpleHTTPRequestHandler): | |
def end_headers (self): | |
self.send_header('Access-Control-Allow-Origin', '*') | |
SimpleHTTPRequestHandler.end_headers(self) | |
if __name__ == '__main__': | |
test(CORSRequestHandler, HTTPServer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice code. Works very nicely!
One question: What is the purpose of wrapping the code in
test()?
I'm not sure what that does.edit: I see now
test
is a method in thehttp.server
module that runs the server.