Python simple server for testing complex sites
Posted by mholmes on 18 Feb 2020 in Labs, Activity log, Documentation
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 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') return super(CORSRequestHandler, self).end_headers() # If you don't need remote resources, just use this: #httpd = http.server.HTTPServer(('localhost', 4443), http.server.SimpleHTTPRequestHandler) httpd = http.server.HTTPServer(('localhost', 4443), CORSRequestHandler) httpd.socket = ssl.wrap_socket (httpd.socket, certfile='/home/mholmes/WorkData/scripts/pyserve/server.pem', 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.