To begin with: let’s set up our request context. This is essentially the environment in which our simulated web application will run. To do this, we need to import a few modules that allow us to handle HTTP requests and responses. Here’s some code to get you started:
# Setting up the request context
# Importing necessary modules for handling HTTP requests and responses
from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi
import os
# Defining a class for our web application, inheriting from BaseHTTPRequestHandler
class MyWebApp(BaseHTTPRequestHandler):
# Defining a method for handling GET requests
def do_GET(self):
# Checking if the requested path is the root path
if self.path == '/':
# Sending a 200 response code
self.send_response(200)
# Setting the content type header to text/html
self.send_header('Content-type', 'text/html')
# Ending the headers
self.end_headers()
# Writing a welcome message to the response body and encoding it
self.wfile.write('<h1>Welcome to my fake web app!</h1>'.encode())
# Checking if the requested path is the about path
elif self.path == '/about':
# Sending a 200 response code
self.send_response(200)
# Setting the content type header to text/html
self.send_header('Content-type', 'text/html')
# Ending the headers
self.end_headers()
# Writing an about message to the response body and encoding it
self.wfile.write('<h1>About this fake web app</h1>'.encode())
# If the requested path is not the root or about path, send a 404 response code
else:
self.send_response(404)
# Setting the content type header to text/html
self.send_header('Content-type', 'text/html')
# Ending the headers
self.end_headers()
# Writing a page not found message to the response body and encoding it
self.wfile.write('<h1>Page not found!</h1>'.encode())
In this code, we’re defining a new class called `MyWebApp`, which inherits from the built-in `BaseHTTPRequestHandler`. This allows us to override some of its methods and customize our own behavior. In particular, we’ve implemented the `do_GET()` method, which handles GET requests for two different paths: ‘/’ (the homepage) and ‘/about’.
Now that we have our request context set up, let’s run it! We can do this by creating an instance of our `MyWebApp` class and passing it to the built-in HTTP server. Here’s some code to get you started:
# Import the necessary modules
from http.server import BaseHTTPRequestHandler, HTTPServer
# Create a class for our web app, inheriting from BaseHTTPRequestHandler
class MyWebApp(BaseHTTPRequestHandler):
# Define a method to handle GET requests for the homepage
def do_GET(self):
# Check if the requested path is the homepage
if self.path == '/':
# Set the response status code to 200 (OK)
self.send_response(200)
# Set the response headers
self.send_header('Content-type', 'text/html')
self.end_headers()
# Send the response body
self.wfile.write(b'<h1>Welcome to my web app!</h1>')
# Check if the requested path is the about page
elif self.path == '/about':
# Set the response status code to 200 (OK)
self.send_response(200)
# Set the response headers
self.send_header('Content-type', 'text/html')
self.end_headers()
# Send the response body
self.wfile.write(b'<h1>About page</h1>')
# If the requested path is not recognized, send a 404 (Not Found) response
else:
self.send_error(404)
# Create an instance of our web app and pass it to the built-in HTTP server
server = HTTPServer(('localhost', 8000), MyWebApp)
# Print a message to indicate that the web app is starting
print("Starting web app on port 8000...")
try:
# Start the server and keep it running until a keyboard interrupt occurs
server.serve_forever()
except KeyboardInterrupt:
# If a keyboard interrupt occurs, print a message and close the server socket
print("Stopping web app...")
server.socket.close()
In this code, we’re creating a new HTTP server instance and passing it our `MyWebApp` class as well as the IP address (‘localhost’) and port (8000). We then start the server using its built-in `serve_forever()` method. If you run this script in your terminal or command prompt, you should see a message that says “Starting web app on port 8000…”.
To test our simulated web application, open up your favorite browser and navigate to http://localhost:8000/. You should see the homepage with a welcome message! If you go to http://localhost:8000/about/, you’ll see some information about our fake app. And if you try to access any other page (like http://localhost:8000/random), you’ll get an error message saying “Page not found!”
Who needs servers when you have Python?