create a http server with a options route in python

Here's a simple example of creating an HTTP server with an OPTIONS route in Python using the built-in http.server module:

main.py
from http.server import HTTPServer, BaseHTTPRequestHandler

class RequestHandler(BaseHTTPRequestHandler):
    
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Allow', 'OPTIONS')
        self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'Hello, world!')

if __name__ == '__main__':
    server = HTTPServer(('localhost', 8000), RequestHandler)
    print('Starting server at http://localhost:8000')
    server.serve_forever()
670 chars
21 lines

In this example, we define a custom request handler by subclassing BaseHTTPRequestHandler and overriding the do_OPTIONS and do_GET methods. do_OPTIONS handles requests with the OPTIONS verb and sets the appropriate headers to allow CORS. do_GET handles GET requests and responds with a simple "Hello, world!" message.

We then create an instance of HTTPServer and pass in our request handler class. We bind the server to localhost on port 8000 and start the server using the serve_forever method.

Note that this is a very basic example and in a real-world application, you would likely want to add more routes and logic to handle various types of requests.

gistlibby LogSnag