Generate a beginner-friendly course with an introduction, 3-5 lessons, and mini-challenges after each lesson about "creating an http server using python". Structure it clearly with titles, steps, chapters, exercises, and resources that user can use for the exercise.
Assistant
Beginner-Friendly Course: Creating an HTTP Server Using Python
Course Overview
This course will guide you through creating a simple HTTP server using Python. You'll learn step-by-step how to set up the server, handle requests, serve web pages, and understand the basics of HTTP communication from a Python perspective. Each lesson will include a mini-challenge to reinforce your learning with hands-on practice.
Introduction
What is an HTTP Server?
An HTTP server is a program that listens for requests from clients (like web browsers) and serves responses (like web pages). By creating your own HTTP server using Python, you’ll understand how web communication works and gain foundational programming skills.
Why Python?
Python offers built-in modules that make it very easy to create HTTP servers without needing external libraries. It is great for beginners due to its readability and simplicity.
Lesson 1: Setting Up a Basic HTTP Server
What You Will Learn
How to use Python’s built-in http.server module
How to start a simple HTTP server that serves files from a directory
How to stop the server
Steps
Open your terminal or command prompt.
Navigate to the directory you want to serve files from.
Run the following command if you have Python 3 installed:
bash
python3 -m http.server 8000
Open your web browser and go to http://localhost:8000.
You should see a list of files in the directory, served by your simple HTTP server.
To stop the server, go back to your terminal and press Ctrl + C.
Explanation
The command starts an HTTP server on port 8000.
The server serves files from the current directory.
Accessing localhost on the specified port shows the content served.
Mini-Challenge 1
Change to a different directory with some files (like images, HTML, or text files).
Start the HTTP server again in that directory.
Access different files through your browser to understand what is being served.
How to write a simple Python script to create an HTTP server
How to handle GET requests
How to serve a custom message instead of files
Steps
Create a new Python file, e.g., my_server.py.
Add the following code:
python
from http.server import BaseHTTPRequestHandler, HTTPServer
class SimpleHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200) # HTTP status code 200 OK
self.send_header('Content-type', 'text/html')
self.end_headers()
# Write a simple HTML response
self.wfile.write(b"<html><body><h1>Hello, this is my HTTP Server!</h1></body></html>")
def run(server_class=HTTPServer, handler_class=SimpleHandler):
server_address = ('', 8000) # Serve on all addresses, port 8000
httpd = server_class(server_address, handler_class)
print("Starting httpd on port 8000...")
httpd.serve_forever()
if __name__ == '__main__':
run()
Run the script:
bash
python3 my_server.py
Open your browser at http://localhost:8000.
You should see the "Hello, this is my HTTP Server!" message.
Explanation
You created a class SimpleHandler to handle GET requests.
do_GET method handles what happens when the client sends a GET request.
Instead of serving files, it sends a simple HTML message.
The server runs forever until interrupted.
Mini-Challenge 2
Change the message to be more personalized. For example: "Welcome to [Your Name]'s HTTP Server!"
Modify the message to include current date and time (hint: look up Python’s datetime module).
Restart your server and verify the new message appears.
How to serve external HTML files instead of hardcoding HTML strings.
How to read files in Python and send their contents as a response.
Steps
Create a folder named web in the same directory as your my_server.py.
Inside the web folder, create index.html and about.html.
Example index.html:
html
<!DOCTYPE html>
<html>
<head><title>Home</title></head>
<body>
<h1>Welcome to the Home Page</h1>
<p>This content is served from index.html file.</p>
</body>
</html>
Example about.html:
html
<!DOCTYPE html>
<html>
<head><title>About</title></head>
<body>
<h1>About Us</h1>
<p>This page explains about the HTTP Server project.</p>
</body>
</html>
Modify your Python server code:
python
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
class SimpleHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/' or self.path == '/index.html':
self.serve_file('web/index.html')
elif self.path == '/about' or self.path == '/about.html':
self.serve_file('web/about.html')
else:
self.send_error(404, "File Not Found")
def serve_file(self, filepath):
try:
with open(filepath, 'rb') as f:
content = f.read()
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(content)
except FileNotFoundError:
self.send_error(404, "File Not Found")
def run(server_class=HTTPServer, handler_class=SimpleHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
print("Serving on port 8000...")
httpd.serve_forever()
if __name__ == '__main__':
run()