How to customize the server?

To customize the http.server module in Python, you can create a subclass of http.server.SimpleHTTPRequestHandler or http.server.BaseHTTPRequestHandler. Here’s how you can do it:

  1. Subclassing the Handler: Create your own handler class to override methods like do_GET() or do_POST() to customize the behavior.

  2. Customizing Responses: You can modify the response headers, status codes, and content based on your requirements.

Here’s a simple example of a customized HTTP server:

from http.server import BaseHTTPRequestHandler, HTTPServer

class CustomHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)  # Send HTTP status code 200 (OK)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(b"<html><body><h1>Hello, World!</h1></body></html>")

def run(server_class=HTTPServer, handler_class=CustomHandler, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f'Serving on port {port}...')
    httpd.serve_forever()

if __name__ == "__main__":
    run()

Explanation:

  • CustomHandler: This class overrides the do_GET() method to send a custom HTML response.
  • run() function: Sets up and starts the server on the specified port.

You can further customize the server by adding more methods or handling different HTTP methods (like POST, PUT, DELETE) as needed.

0 Comments

no data
Be the first to share your comment!