Here is an example of a simple HTTP server using Python's built-in http.server
module. This server will handle basic GET and POST requests.
Basic HTTP Server Example
import http.server
import socketserver
PORT = 8000
class MyRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(b"<html><head><title>My HTTP Server</title></head>")
self.wfile.write(b"<body><h1>GET request received!</h1></body></html>")
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
response = f"<html><head><title>My HTTP Server</title></head><body><h1>POST request received!</h1><p>{post_data.decode()}</p></body></html>"
self.wfile.write(response.encode())
with socketserver.TCPServer(("", PORT), MyRequestHandler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
How to Run the Server
Save the Script: Save the script to a file, for example
simple_http_
server.py
.Run the Script:
python simple_http_server.py
Access the Server: Open a web browser and go to
http://localhost:8000
.
Server Explanation
Import Modules: Import
http.server
for handling HTTP requests andsocketserver
for creating a TCP server.Set the Port: The server will run on port 8000.
Define Request Handler:
MyRequestHandler
inherits fromSimpleHTTPRequestHandler
and overridesdo_GET
anddo_POST
methods to handle GET and POST requests respectively.do_GET: Responds with a simple HTML page for GET requests.
do_POST: Reads the posted data, responds with an HTML page displaying the received data.
Create and Run the Server: Use
socketserver.TCPServer
to bind the handler to the specified port and start serving requests.
Customizing the Server
You can customize the server further by adding more request handling methods (e.g., do_PUT
, do_DELETE
), serving different content types, or implementing additional logic to process the requests.
Handling JSON Data in POST Requests
If you want to handle JSON data in POST requests, you can modify the do_POST
method as follows:
import json
class MyRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
try:
json_data = json.loads(post_data)
response = f"<html><head><title>My HTTP Server</title></head><body><h1>POST request received!</h1><p>{json.dumps(json_data, indent=4)}</p></body></html>"
except json.JSONDecodeError:
response = f"<html><head><title>My HTTP Server</title></head><body><h1>POST request received!</h1><p>Invalid JSON</p></body></html>"
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(response.encode())
In this modification, the server tries to parse the POST data as JSON and includes the formatted JSON in the response. If the data is not valid JSON, it responds with an error message.
This is just a super basic example of an HTTP server, feel free to copy the code and modify it to suit your needs. Listed below are a few ideas on how to improve it.
Improvements
Here are some recommended improvements to the basic Python HTTP server to make it more robust, secure, and feature-rich:
Error Handling: Add error handling to manage unexpected issues gracefully.
Logging: Implement logging to keep track of requests and errors.
Security Enhancements: Add basic security measures such as request validation and protection against common vulnerabilities.
Configuration: Use a configuration file or environment variables for settings like port and logging levels.
Modular Code: Refactor the code to be more modular, separating different concerns.
Static File Serving: Enhance the server to serve static files from a specified directory.
Enhanced Request Handling: Handle more HTTP methods and improve POST data handling.
Threading: Use threading or multiprocessing to handle multiple requests concurrently.