Skip to content

Instantly share code, notes, and snippets.

@toonetown
Last active September 7, 2022 21:11
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save toonetown/6603e97bb64c52fa9590 to your computer and use it in GitHub Desktop.
Save toonetown/6603e97bb64c52fa9590 to your computer and use it in GitHub Desktop.
A quick-and-dirty python web server
#!/usr/bin/python3
import http.server, ssl, argparse, re
from tempfile import mkdtemp
from shutil import rmtree
from contextlib import contextmanager
from os.path import exists, join, abspath
@contextmanager
def TemporaryDirectory():
name = mkdtemp()
try:
yield name
finally:
rmtree(name)
def RunServer(HostName, Port,
HandlerClass = http.server.SimpleHTTPRequestHandler,
ServerClass = http.server.HTTPServer):
HandlerClass.extensions_map.update({
'.pac': 'application/x-ns-proxy-autoconfig'
});
httpd = ServerClass((HostName, Port), HandlerClass)
Proto = 'HTTP'
sa = httpd.socket.getsockname()
print("Serving " + Proto + " on " + str(sa[0]) + " port " + str(sa[1]) + "...")
print("")
httpd.serve_forever()
def Execute(HostName = None, Port = None,
HandlerClass = http.server.SimpleHTTPRequestHandler,
ServerClass = http.server.HTTPServer):
if HostName is None: HostName = '0.0.0.0'
if Port is None: Port = 8000
RunServer(HostName, Port, HandlerClass, ServerClass)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description = '''
Launches a webserver (HTTP) that serves files from the local directory. When run without
arguments, this program functions like python's http.server.
''',
)
parser.add_argument('--host', action = 'store', dest = 'HostName',
help = 'Sets the host name to listen on (default: 0.0.0.0)')
parser.add_argument('--port', action = 'store', dest = 'Port', type = int,
help = 'Sets the port to listen on (default: 8000 for HTTP)')
args = parser.parse_args()
Execute(args.HostName, args.Port)
@kidharb
Copy link

kidharb commented Mar 9, 2020

You saved me from having to install a fully blown webserver.
I love it!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment