Alright ! Let’s talk about Python HTTP server module but with caution. While it’s an easy-to-use and readily available tool for creating web servers in Python, there are some important limitations to consider before using it for production purposes. The official documentation warns that http.server only implements basic security checks, which means you should be careful when handling sensitive data or dealing with high traffic websites.
To use this module, import it:
# Import the http.server module to use its functionality
import http.server
# Create a class called SimpleHTTPRequestHandler that inherits from the BaseHTTPRequestHandler class
class SimpleHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
# Define a function called do_GET that handles GET requests
def do_GET(self):
# Set the response status code to 200, indicating a successful request
self.send_response(200)
# Set the response headers to indicate that the content type is text/html
self.send_header('Content-type', 'text/html')
# End the response headers
self.end_headers()
# Write a message to the response body
self.wfile.write(b'Hello, world!')
# Create a server instance using the SimpleHTTPRequestHandler class
server = http.server.HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
# Start the server and keep it running until it is manually stopped
server.serve_forever()
Now we can create our own request handler class by extending `BaseHTTPRequestHandler`. This is where the magic happens all of the HTTP requests will be handled through methods defined in this class. Let’s take a look at an example:
# Create a custom request handler class by extending the BaseHTTPRequestHandler class
class MyRequestHandler(http.server.BaseHTTPRequestHandler):
# Define some properties for our handler
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.my_property = "This is a property"
# Override the do_GET method to handle GET requests
def do_GET(self):
# Check if the requested path is '/'
if self.path == '/':
# Send a 200 response code
self.send_response(200)
# Set the content type header to 'text/plain'
self.send_header('Content-type', 'text/plain')
# End the headers
self.end_headers()
# Write the response body
self.wfile.write("Hello, world!".encode())
# Override the do_POST method to handle POST requests
def do_POST(self):
# Check if the requested path is '/'
if self.path == '/':
# Get the content length from the request headers
content_length = int(self.headers['Content-Length'])
# Read the request body and decode it
body = self.rfile.read(content_length).decode()
# Print the received body
print("Received: ", body)
# Create an instance of our handler class and set up the server
handler = MyRequestHandler
# Create an HTTP server on localhost, port 8000, using our custom handler
server = HTTPServer(('localhost', 8000), handler)
# Print a message to indicate the server is starting
print("Starting server, use 'Ctrl+C' to stop")
try:
# Start the server and keep it running until interrupted
server.serve_forever()
except KeyboardInterrupt:
# If the server is interrupted, print a message and stop the server
print("Stopping server...")
finally:
# Close the server socket
server.socket.close()
In this example, we’re creating an instance of our `MyRequestHandler` class and passing it to the constructor for the HTTPServer object. We’re also setting up a simple server on localhost at port 8000. When you run this script, open your browser and navigate to http://localhost:8000 you should see “Hello, world!” in response!
And that’s it! You now have a basic understanding of how to use the Python HTTP server module with caution. Remember, while it’s an easy-to-use tool for creating web servers in Python, its limitations mean it may not be suitable for production purposes.