36 lines
1.2 KiB
Python
36 lines
1.2 KiB
Python
from __future__ import annotations
|
|
|
|
import ssl
|
|
import threading
|
|
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
|
|
from pathlib import Path
|
|
from typing import Tuple
|
|
|
|
|
|
class _Handler(SimpleHTTPRequestHandler):
|
|
# Allow passing a base directory at construction time
|
|
def __init__(self, *args, directory: str | None = None, **kwargs):
|
|
super().__init__(*args, directory=directory, **kwargs)
|
|
|
|
|
|
def start_https_static(host: str, port: int, certfile: str, keyfile: str, docroot: str) -> Tuple[ThreadingHTTPServer, threading.Thread]:
|
|
"""Start a simple HTTPS static file server in a background thread.
|
|
|
|
Returns the (httpd, thread). Caller is responsible for calling httpd.shutdown()
|
|
to stop the server on application exit.
|
|
"""
|
|
docroot_path = str(Path(docroot).resolve())
|
|
|
|
def handler(*args, **kwargs):
|
|
return _Handler(*args, directory=docroot_path, **kwargs)
|
|
|
|
httpd = ThreadingHTTPServer((host, port), handler)
|
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
ctx.load_cert_chain(certfile=certfile, keyfile=keyfile)
|
|
httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
|
|
|
|
t = threading.Thread(target=httpd.serve_forever, name="https-static", daemon=True)
|
|
t.start()
|
|
return httpd, t
|
|
|