Skip to content

Instantly share code, notes, and snippets.

@fmunirdev
Forked from iktakahiro/server4spa.py
Last active September 17, 2022 11:56
Show Gist options
  • Save fmunirdev/7055af668e36fb895dc84c0fe66d73fa to your computer and use it in GitHub Desktop.
Save fmunirdev/7055af668e36fb895dc84c0fe66d73fa to your computer and use it in GitHub Desktop.
Python3 http.server for Single Page Application
#!/usr/bin/env python
# Inspired by https://gist.github.com/jtangelder/e445e9a7f5e31c220be6
# Python3 http.server for Single Page Application
import os
import socketserver
import multiprocessing as mp
import re
import urllib.parse
import pathlib
from http.server import SimpleHTTPRequestHandler
PORT = 8000
BASE_PATH = os.path.dirname(__file__)
class HTTPHandler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=os.path.join(BASE_PATH, "dist"), **kwargs)
def do_GET(self):
# serve sample data response as json
if self.path.startswith("/api/people"):
id = self.path.split("/")[-1]
filename = f"cached-responses/{id}.json"
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
with open(os.path.join(BASE_PATH, filename), "rb") as f:
self.wfile.write(f.read())
else:
pattern = re.compile(
".png|.jpg|.jpeg|.js|.css|.ico|.gif|.svg", re.IGNORECASE
)
url_parts = urllib.parse.urlparse(self.path)
request_file_path = pathlib.Path(url_parts.path.strip("/"))
ext = request_file_path.suffix
if not request_file_path.is_file() and not pattern.match(ext):
self.path = "index.html"
super().do_GET()
def start_server():
with socketserver.TCPServer(("", PORT), HTTPHandler) as httpd:
print("Serving at port:", PORT)
httpd.serve_forever()
if __name__ == "__main__":
# Start in a background process, and terminate it conditionally.
proc = mp.Process(target=start_server, args=())
proc.start()
proc.terminate()
# Or just start in the main process.
start_server()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment