Created
August 30, 2022 13:13
-
-
Save fanurs/2fb530d9f09bfa8dad8aa672f9d3d32c to your computer and use it in GitHub Desktop.
Serve HTTP server using Python3
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/env python3 | |
import argparse | |
import functools | |
import http.server | |
import threading | |
class ArgumentParser: | |
def __init__(self): | |
self.parser = argparse.ArgumentParser() | |
self.parser.add_argument("port", type=int, default=9090, help="port to listen on") | |
self.parser.add_argument("-d", "--directory", type=str, default=".", help="directory to serve") | |
self.args = self.parser.parse_args() | |
class HttpServerThread(threading.Thread): | |
def __init__(self, address, target_dir): | |
super().__init__() | |
self.address = address | |
self.target_dir = target_dir | |
self.server = http.server.HTTPServer( | |
address, | |
functools.partial(http.server.SimpleHTTPRequestHandler, directory=self.target_dir), | |
) | |
self.start() | |
def run(self): | |
self.server.serve_forever(poll_interval=1) | |
def stop(self): | |
self.server.shutdown() | |
if __name__ == "__main__": | |
args = ArgumentParser().args | |
print('HTTP server running on port {}'.format(args.port)) | |
http_server = HttpServerThread( | |
address=('0.0.0.0', args.port), | |
target_dir=args.directory, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment