Last active
September 7, 2022 21:11
-
-
Save toonetown/6603e97bb64c52fa9590 to your computer and use it in GitHub Desktop.
A quick-and-dirty python web server
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
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You saved me from having to install a fully blown webserver.
I love it!!!