add cors headers to a http server with a specific origin and methods in python

To add CORS headers to an HTTP server with a specific origin and methods in Python, you can create middleware that adds the appropriate headers to each request. Here's an example of how to do this using the built-in http.server module:

main.py
from http.server import HTTPServer, SimpleHTTPRequestHandler

class CORSRequestHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', 'http://your-specific-origin.com')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST')
        super().end_headers()

httpd = HTTPServer(('localhost', 8000), CORSRequestHandler)
httpd.serve_forever()
415 chars
11 lines

In this example, we've created a custom CORSRequestHandler class that subclasses SimpleHTTPRequestHandler. In its end_headers() method, we manually set the Access-Control-Allow-Origin and Access-Control-Allow-Methods headers to our desired values. You can customize these values to fit your specific needs.

We then create an instance of HTTPServer, passing in our custom CORSRequestHandler instead of the default SimpleHTTPRequestHandler. Finally, we call serve_forever() on the server instance to start listening for incoming requests.

gistlibby LogSnag