Skip to content

Instantly share code, notes, and snippets.

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 d4rkb1ue/5784173c5c165894c2bf47a416ad96fd to your computer and use it in GitHub Desktop.
Save d4rkb1ue/5784173c5c165894c2bf47a416ad96fd to your computer and use it in GitHub Desktop.
Python SimpleHTTPServer: Serve specific directory and send 204 instead of 404 when file not found
python -m server.py --dir ~/Documents --port 5000
# #!/usr/bin/env python2
import posixpath
import argparse
import urllib
import os
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer
class RootedHTTPServer(HTTPServer):
def __init__(self, base_path, *args, **kwargs):
HTTPServer.__init__(self, *args, **kwargs)
self.RequestHandlerClass.base_path = base_path
class RootedHTTPRequestHandler(SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
# print(vars(self), self.headers.getplist())
def translate_path(self, path):
path = posixpath.normpath(urllib.unquote(path))
words = path.split('/')
words = filter(None, words)
path = self.base_path
for word in words:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in (os.curdir, os.pardir):
continue
path = os.path.join(path, word)
return path
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:
# make 404 to 204
self.send_response(204, "No Content")
self.end_headers()
return f
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.end_headers()
return f
def test(HandlerClass=RootedHTTPRequestHandler, ServerClass=RootedHTTPServer):
parser = argparse.ArgumentParser()
parser.add_argument('--port', '-p', default=8000, type=int)
parser.add_argument('--dir', '-d', default=os.getcwd(), type=str)
args = parser.parse_args()
server_address = ('', args.port)
httpd = ServerClass(args.dir, server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
test()
base on https://gist.github.com/diegosorrilha/812787c01b65fde6dec870ab97212abd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment