Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python SimpleHTTPServer with CORS, supporting both Python 2 and 3
#!/usr/bin/env python
# Usage: python cors_http_server.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)
@anselmobattisti
Copy link

anselmobattisti commented Dec 8, 2018

You saved my life!

Loading

@mflux
Copy link

mflux commented Jun 8, 2019

This does not work with python 3

Loading

@khalidx
Copy link
Author

khalidx commented Jun 9, 2019

@mflux yup, it was for Python 2. I updated it to work with both Python 2 and 3. Thanks!

Loading

@AlbaraaKhayat
Copy link

AlbaraaKhayat commented Feb 10, 2020

Works great, thanks!

Loading

@khalidx
Copy link
Author

khalidx commented Feb 19, 2020

@mflux it should seamlessly work for both python 2 and 3 now (as of June 8, 2019)
@anselmobattisti @AlbaraaKhayat glad I could help!

Loading

@Jia-SH
Copy link

Jia-SH commented Jan 13, 2021

it works only in localhost.
change line 10:
test_orig(*args, port=int(sys.argv[1]) if len(sys.argv) > 1 else 8000), bind="0.0.0.0"

Loading

@Ragnoroct
Copy link

Ragnoroct commented Sep 23, 2021

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 the http.server module that runs the server.

Loading

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