Unfortunately, a simple HTTP server is really so simple that it does not allow any configuration, especially for the headers it sends. However, you can create a simple HTTP server yourself using most of the SimpleHTTPRequestHandler and just add the header you SimpleHTTPRequestHandler .
To do this, simply create a simple-cors-http-server.py (or any other) file and, depending on your version of Python, put one of the following codes inside.
Then you can make python simple-cors-http-server.py and it will start your modified server, which will set the CORS header for each response.
With the hangout at the top, make the file executable and put it in PATH, and you can just run it using simple-cors-http-server.py too.
Python 3 solution
Python 3 uses SimpleHTTPRequestHandler and HTTPServer from the http.server module to start the server:
#!/usr/bin/env python3 from http.server import HTTPServer, SimpleHTTPRequestHandler, test import sys class CORSRequestHandler (SimpleHTTPRequestHandler): def end_headers (self): self.send_header('Access-Control-Allow-Origin', '*') SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': test(CORSRequestHandler, HTTPServer, port=int(sys.argv[1]) if len(sys.argv) > 1 else 8000)
Python 2 solution
Python 2 uses SimpleHTTPServer.SimpleHTTPRequestHandler and the BaseHTTPServer module to start the server.
#!/usr/bin/env python2 from SimpleHTTPServer import SimpleHTTPRequestHandler import BaseHTTPServer class CORSRequestHandler (SimpleHTTPRequestHandler): def end_headers (self): self.send_header('Access-Control-Allow-Origin', '*') SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)
Python 2 & 3 Solution
If you need compatibility for both Python 3 and Python 2, you can use this polyglot script, which works in both versions. It first tries to import from Python 3 locations, and otherwise returns to Python 2:
#!/usr/bin/env python try: # 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: # 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)