Last active
August 29, 2015 14:23
-
-
Save suligap/fcfe3cca11654db590bf to your computer and use it in GitHub Desktop.
This file contains 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
""" | |
SimpleHTTPServer that adds a | |
Access-Control-Allow-Origin: * | |
header to the response. | |
Run it like https://docs.python.org/2/library/simplehttpserver.html#module-SimpleHTTPServer | |
""" | |
import os | |
from SimpleHTTPServer import test, SimpleHTTPRequestHandler | |
class RH(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: | |
# Always read in binary mode. Opening files in text mode may cause | |
# newline translations, making the actual size of the content | |
# transmitted *less* than the content-length! | |
f = open(path, 'rb') | |
except IOError: | |
self.send_error(404, "File not found") | |
return None | |
try: | |
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 | |
except: | |
f.close() | |
raise | |
test(HandlerClass=RH) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment