Skip to content

Instantly share code, notes, and snippets.

@iktakahiro
Last active January 28, 2024 13:08
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 iktakahiro/2c48962561ea724f1e9d to your computer and use it in GitHub Desktop.
Save iktakahiro/2c48962561ea724f1e9d 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 urllib.parse
import http.server
import socketserver
import re
from pathlib import Path
HOST = ('0.0.0.0', 8000)
pattern = re.compile('.png|.jpg|.jpeg|.js|.css|.ico|.gif|.svg', re.IGNORECASE)
class Handler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
url_parts = urllib.parse.urlparse(self.path)
request_file_path = 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'
return http.server.SimpleHTTPRequestHandler.do_GET(self)
httpd = socketserver.TCPServer(HOST, Handler)
httpd.serve_forever()
@tomsaleeba
Copy link

Thanks 😄

@laymanmu
Copy link

thanks for this easy example 👍

@adamf-sendblocks
Copy link

👑

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