To handle POST requests in a custom HTTP server using the http.server module in Python, you need to override the do_POST() method in your request handler class. Here’s an example demonstrating how to do this:
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
class CustomHandler(BaseHTTPRequestHandler):
def do_POST(self):
# Set response status code
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
# Read the content length and data
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
# Process the received data (for example, convert it to a dictionary)
data = json.loads(post_data)
# Create a response (echoing back the received data)
response = {
'message': 'Data received successfully!',
'data': data
}
# Send the response back to the client
self.wfile.write(json.dumps(response).encode('utf-8'))
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:
- do_POST() Method: This method is called when a POST request is received.
- It first sends a 200 OK response.
- It reads the content length from the headers and then reads the POST data.
- The data is processed (in this case, parsed as JSON).
- A response is created and sent back to the client.
Testing the Server:
You can test this server using curl or any HTTP client. For example, to send a POST request with JSON data:
curl -X POST http://localhost:8000 -H "Content-Type: application/json" -d '{"key": "value"}'
This will return a JSON response confirming the data was received.
