Search notes:

Python Webserver for CORS compatible HTTP requests

The following Python script (which I found on Francesco Pira's blog) starts a webserver that allows CORS request.
This webserver takes zero, one (port, default: 8080) or two (port and server address, default: 0.0.0.0) parameters:
$ ./websrv-cors.py
$ ./websrv-cors.py 7777            # listen on port 7777
$ ./websrv-cors.py 7777 localhost  # listen on port 7777, on localhost

websrv-cors.py

# Found at
#
#   https://fpira.com/blog/2020/05/python-http-server-with-cors
#
from http.server import HTTPServer, SimpleHTTPRequestHandler
import sys


class CORSRequestHandler(SimpleHTTPRequestHandler):

    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin' , '*')
        self.send_header('Access-Control-Allow-Methods', '*')
        self.send_header('Access-Control-Allow-Headers', '*')
        self.send_header('Cache-Control'                , 'no-store, no-cache, must-revalidate')
        return super(CORSRequestHandler, self).end_headers()

    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

port = int(sys.argv[1]) if len(sys.argv) > 1 else  8080
host =     sys.argv[2]  if len(sys.argv) > 2 else '0.0.0.0'

httpd = HTTPServer((host, port), CORSRequestHandler)
httpd.serve_forever()
Github repository scripts-and-utilities, path: /websrv-cors.py

See also

CORS
Adding HTTP response headers to a Python (http.server.SimpleHTTPRequestHandler) webserver.
Other scripts

Index