If you want to create a basic web server using Python, the SimpleHTTPRequestHandler is your go-to guy. This class allows us to handle HTTP requests with ease, without having to worry about all that ***** low-level stuff like sockets and protocols.
Here’s how it works: first, we import the necessary modules (including our trusty friend `SimpleHTTPRequestHandler`) and create a new instance of the class. Then, we define some custom methods for handling specific requests (like GET or POST), and finally, we start up the server using the built-in HTTP library.
Here’s an example:
# Import necessary modules
from http.server import SimpleHTTPRequestHandler, HTTPServer
import os
# Create a new instance of the SimpleHTTPRequestHandler class
class MyHandler(SimpleHTTPRequestHandler):
# Define method for handling GET requests
def do_GET(self):
# Send a 200 response code
self.send_response(200)
# Set the content type to HTML
self.send_header('Content-type', 'text/html')
# End the headers
self.end_headers()
# Write a simple HTML message to the client
self.wfile.write(b'<h1>Hello, world!</h1>')
# Define method for handling POST requests
def do_POST(self):
# Currently not handling POST requests, so pass
pass
# Define method for handling PUT requests
def do_PUT(self):
# Currently not handling PUT requests, so pass
pass
# Define method for handling DELETE requests
def do_DELETE(self):
# Currently not handling DELETE requests, so pass
pass
# Check if the script is being run directly
if __name__ == '__main__':
# Create an instance of the HTTPServer class, passing in the host and port
server = HTTPServer(('localhost', 80), MyHandler)
# Print a message to indicate the server is starting
print("Starting web server...")
try:
# Start the server and keep it running until a keyboard interrupt occurs
server.serve_forever()
except KeyboardInterrupt:
# If a keyboard interrupt occurs, close the server and print a message
server.server_close()
print("Stopping web server...")
In this example, we’ve created a custom handler class called `MyHandler`, which inherits from the SimpleHTTPRequestHandler class. We then define some custom methods for handling specific requests (like GET or POST), and finally, start up the server using the built-in HTTP library.
And that’s it! With just a few lines of code, you can create a basic web server in Python that handles common HTTP requests like GET, POST, PUT, and DELETE. Pretty cool, huh?