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

To add CORS headers to a http server with a specific origin in Python, you can use the cors library. Here's a sample code to enable CORS headers for a specific origin:

main.py
from http.server import HTTPServer, BaseHTTPRequestHandler
from cors import *

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        
        # Add CORS headers for a specific origin
        self.send_header('Access-Control-Allow-Origin', 'https://example.com')
        self.send_header('Access-Control-Allow-Methods', 'GET')
        self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-type')

        self.end_headers()
        self.wfile.write(b'Hello, world!')

httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
httpd.serve_forever()
696 chars
19 lines

In this code, we created a custom HTTP request handler (SimpleHTTPRequestHandler) that extends the BaseHTTPRequestHandler class. We then overrode the do_GET method to add our custom headers.

To add CORS headers, we use the self.send_header method to add the required headers. In this example, we added CORS headers for a specific origin (https://example.com) and allowed the GET method with the Access-Control-Allow-Methods header.

Finally, we create an instance of HTTPServer and pass in our custom request handler. We then call serve_forever to start the server and listen for incoming requests.

gistlibby LogSnag