Skip to content

Instantly share code, notes, and snippets.

@janaz
Forked from enjalot/cors_server.py
Last active April 23, 2016 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janaz/0949c72c4b6d1987bb4ca33a5c77edad to your computer and use it in GitHub Desktop.
Save janaz/0949c72c4b6d1987bb4ca33a5c77edad to your computer and use it in GitHub Desktop.
Allow CORS with python simple http server
import sys
import SimpleHTTPServer
class CORSHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def send_head(self):
path = self.translate_path(self.path)
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
for index in "index.html", "index.htm":
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Content-Length", str(fs[6]))
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
return f
if __name__ == "__main__":
import os
import SocketServer
PORT = (len(sys.argv) > 1 and int(sys.argv[1])) or 31338
Handler = CORSHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment