I often have a need to serve a local directory via HTTP. In the old days the built-in Python webserver was enough, but at some point browsers became more aggressive about concurrent connections and the single-threaded `python -m SimpleHTTPServer` would just get stuck if it received two requests at once.<p>As a workaround, I wrote a small wrapper script that would enable multi-threading for SimpleHTTPServer.<p>~/bin/http-cwd , Python 2 version (original):<p><pre><code> #!/usr/bin/python
import argparse
import BaseHTTPServer
import SimpleHTTPServer
import SocketServer
import sys
class ThreadedHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
pass
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument(
"--port", type = int, nargs = "?",
action = "store", default = 8000,
help = "Specify alternate port [default: 8000]",
)
parser.add_argument(
"--iface", type = str, nargs = "?",
action = "store", default = "127.0.0.1",
help = "Specify iface [default: 127.0.0.1]",
)
args = parser.parse_args(argv[1:])
server_address = (args.iface, args.port)
srv = ThreadedHTTPServer(server_address, SimpleHTTPServer.SimpleHTTPRequestHandler)
sa = srv.socket.getsockname()
print "Serving http://%s:%r ..." % (sa[0], sa[1])
srv.serve_forever()
if __name__ == "__main__":
sys.exit(main(sys.argv))
</code></pre>
Python 3 version (necessary for platforms that have dropped Python 2, such as macOS):<p><pre><code> #!/usr/bin/python3
import argparse
import http.server
import socketserver
import sys
class ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
pass
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument(
"--port", type = int, nargs = "?",
action = "store", default = 8000,
help = "Specify alternate port [default: 8000]",
)
parser.add_argument(
"--iface", type = str, nargs = "?",
action = "store", default = "127.0.0.1",
help = "Specify iface [default: 127.0.0.1]",
)
args = parser.parse_args(argv[1:])
server_address = (args.iface, args.port)
srv = ThreadedHTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
sa = srv.socket.getsockname()
print("Serving http://%s:%r ..." % (sa[0], sa[1]))
srv.serve_forever()
if __name__ == "__main__":
sys.exit(main(sys.argv))</code></pre>