create a http server with a put route in python

To create an HTTP server with a PUT route in Python, we can use the built-in http.server module. Here's an example code to create a simple HTTP server that listens on port 8000 and handles PUT requests to the /upload endpoint:

main.py
from http.server import BaseHTTPRequestHandler, HTTPServer

class PutHandler(BaseHTTPRequestHandler):
    
    def do_PUT(self):
        # Gets the length of the incoming data
        content_length = int(self.headers['Content-Length'])
        
        # Reads the data itself, assuming it's in JSON format
        data = json.loads(self.rfile.read(content_length).decode())
        
        # Your PUT handler logic here, e.g.:
        print(f'Received PUT request with data: {data}')
        
        # Sends a response
        self.send_response(200)
        self.end_headers()

def run_server():
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, PutHandler)
    print(f'Starting server at http://{server_address[0]}:{server_address[1]}...')
    httpd.serve_forever()

if __name__ == '__main__':
    run_server()
838 chars
27 lines

In this example, we define a custom handler class PutHandler that inherits from BaseHTTPRequestHandler and overrides the do_PUT method to handle PUT requests. The incoming data is read from the request body and parsed as JSON, and then your custom logic for handling the PUT request can be added.

We then create an instance of HTTPServer with PutHandler and run it indefinitely. You can customize the server address and port as needed.

related categories

gistlibby LogSnag