Log in

HCMC Journal

Python simple server for testing complex sites

: Martin Holmes

This is an updated version of an older post, handling deprecations in Python 3.10; also added the Expires header in 2024-09.

Static sites often require a CORS- and AJAX-supporting server to function properly, so it’s helpful to run one locally. This is the script I’ve put together for doing that:

# This was created based on info from various online instructions sites.
# First you need to create a cert so that SSL will work.
# Generate server.pem with the following command:
#    openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes
# run as follows:
#    python pyserve.py
# in the folder where the web materials are.
# Then in your browser, visit:
#    https://localhost:4443

import http.server
import socket
import ssl

# Not that we're allowing CORS here, because we need to run local sites which 
# use remote resources.
class CORSRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET')
        self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
        self.send_header('Expires', '0')
        return super(CORSRequestHandler, self).end_headers()

httpd = http.server.HTTPServer(('localhost', 4443), CORSRequestHandler)
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.check_hostname = False
ctx.load_cert_chain(certfile='/home/mholmes/scripts/pyserve/server.pem')  # with key inside
httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
httpd.serve_forever()

I usually add an alias link in my .bashrc file like this:

alias pyserve='python ~/WorkData/scripts/pyserve/pyserve.py'

so I can just run pyserve in the folder where the static site is.