Skip to content

Instantly share code, notes, and snippets.

@dipu-bd
Last active December 14, 2020 17:02
Show Gist options
  • Save dipu-bd/043d1dc686ef6c95fbca8c39a2954a68 to your computer and use it in GitHub Desktop.
Save dipu-bd/043d1dc686ef6c95fbca8c39a2954a68 to your computer and use it in GitHub Desktop.
A simple python server to serve website files from a directory. Related: https://gist.github.com/dipu-bd/1183ca6a6f9968853e17bcc7820d895d
#!/usr/bin/env python
import http.server
import os
import socketserver
import time
from argparse import ArgumentParser
start_time = time.time()
#-----------------------------------------------------------------------------#
# Gather Configuration
#-----------------------------------------------------------------------------#
parser = ArgumentParser()
parser.add_argument('-H', '--host', type=str, default='',
help="Hostname")
parser.add_argument('-p', '--port', type=int, default=3000,
help="Port")
parser.add_argument('directory', nargs='?', type=str,
help="Directory to serve")
args = parser.parse_args()
web_dir = os.path.abspath(args.directory or 'dist')
if not os.path.exists(web_dir):
raise FileNotFoundError(web_dir)
os.chdir(web_dir)
print("Serving from", web_dir)
#-----------------------------------------------------------------------------#
# Create HTTP Server
#-----------------------------------------------------------------------------#
class MyHandler(http.server.SimpleHTTPRequestHandler):
def send_head(self):
"""Redirect all requests to /# path."""
path = self.translate_path(self.path)
if self.path in ['', '/'] or os.path.isfile(path):
return super().send_head()
self.send_response(307) # Temporary Redirect
self.send_header("Location", '/#' + self.path)
self.end_headers()
return None
httpd = socketserver.TCPServer((args.host, args.port), MyHandler)
#-----------------------------------------------------------------------------#
# Start HTTP Server
#-----------------------------------------------------------------------------#
print("Serving at http://%s:%s" % (args.host or 'localhost', args.port))
print("-" * 15)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
finally:
httpd.serve_forever
httpd.shutdown()
httpd.server_close()
print()
print("-" * 15)
print("Server stopped.")
print("Uptime %0.3f seconds" % (time.time() - start_time))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment