Mastering Python Web Servers: A Complete Guide from Simple to CGI

So, have you taken your first steps into the world of web development? This sometimes complicated and daunting path can be a lot more fun than you think, especially with Python. Today, we're going to show you how to use the Python We'll meet the many faces of web servers. From simple file servers to CGI servers serving dynamic content, we'll dig into everything you can do with Python. So, let's dive into the world of Python web servers.
Types of Python Web Servers
Python provides a variety of web server implementations. Let's take a closer look at the features and usage of each.
1. SimpleHTTPRequestHandler
It is the simplest and most powerful Python web server. It is primarily used to serve static files.
#simpleServer.py
from http.server import HTTPServer, SimpleHTTPRequestHandler
import os
def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler):
server_address = ('', 8000)
os.chdir('your_directory') # Change to the directory you want to service
httpd = server_class(server_address, handler_class)
print("The server is running at http://localhost:8000/.")
httpd.serve_forever()
if __name__ == '__main__':
run()On Windows, run this code by typing the python simpleServer.py command in a cmd window to serve the files in the specified directory (your_directory) to the web. In a browser, type http://localhost:8000and you'll see a list of files.
2. BaseHTTPRequestHandler
Use it when you need more granular control. You can define how requests are handled.
from http.server import HTTPServer, BaseHTTPRequestHandler
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"<html><body><h1>Welcome to My Server!</h1></body></html>")
def run(server_class=HTTPServer, handler_class=MyHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
print("The server is running at http://localhost:8000/.")
httpd.serve_forever()
if __name__ == '__main__':
run()This server sends a simple HTML page (displaying Welcome to My Server!) in response to every GET request. You can run and verify it as in #1.
3. CGIHTTPRequestHandler
A server that can run Common Gateway Interface (CGI) scripts. Used to generate dynamic content.
from http.server import HTTPServer, CGIHTTPRequestHandler
import os
def run(server_class=HTTPServer, handler_class=CGIHTTPRequestHandler):
server_address = ('', 8000)
handler_class.cgi_directories = ['/cgi-bin']
os.chdir('your_web_root') # Change to your web root directory
httpd = server_class(server_address, handler_class)
print("The CGI server is running at http://localhost:8000/.")
httpd.serve_forever()
if __name__ == '__main__':
run()To use this server, you need to create a 'cgi-bin' directory and put your CGI scripts in it. Now, let's learn more about CGI scripts.
Writing CGI scripts
CGI scripts are programs that generate dynamic content. Let's write a CGI script in Python.
- First, create a directory called 'cgi-bin'.
- Inside it, create a 'hello.py' file and type the following
#!/usr/bin/env python3
print("Content-Type: text/html")
print()
print("<html>")
print("<head><title>Hello CGI</title></head>")
print("<body>")
print("<h1>Hello, CGI World!</h1>")
print("</body>")
print("</html>")- Grant execute permissions to this file (for Unix systems)
chmod +x cgi-bin/hello.pyNow, in your browser, type http://localhost:8000/cgi-bin/hello.pyyou'll see a message that says "Hello, CGI World!".
Code breakdown
Let's take a closer look at each line of the CGI script.
#!/usr/bin/env python3
- This is a shebang line that specifies the interpreter to run this script in.
print("Content-Type: text/html")
- Outputs the HTTP headers. In this case, it tells us that the content type is HTML.
print()
- Output a blank line to separate the header from the body.
The remaining print() statement
- Generate HTML content.
Create dynamic web pages with this simple script. You can also do more complex things like integrate with databases, handle forms, and more.

WSGI Server
The Web Server Gateway Interface (WSGI) defines a standard interface between Python web applications and web servers. WSGI makes it easy to connect a web server and a Python web application.
Here's the wsgiref module for a simple WSGI server example.
from wsgiref.simple_server import make_server
def simple_app(environ, start_response):
status = '200 OK'
headers = [('Content-Type', 'text/plain')]
start_response(status, headers)
response_body = 'Hello, World!'
return [response_body.encode('utf-8')]
Create the # WSGI server
server = make_server('localhost', 8000, simple_app)
print("Serving on port 8000...")
Start the # server
server.serve_forever()This code consists of the following components
simple_appA WSGI application function that processes HTTP requests and generates responses.make_serverFunction to create a WSGI server.server.serve_forever(): Start the server and continue processing requests.
Run Result
When you run this code, the following output appears in the console
Serving on port 8000...This indicates that the server has started successfully and is waiting for requests on port 8000.
Test your server
After running the above code, open the http://localhost:8000you'll see a "Hello, World!" message. This is because the simple_app function is set to return this message for all requests.
How a WSGI server works
- When an HTTP request comes in from a client, the WSGI server receives it.
- The server sends the request information to the
environdictionary and use it to create a WSGI application (simple_app) in the application. start_responsefunction to set the status code and headers.- The WSGI application returns the response body.
- The server sends this response to the client.
In this way, the WSGI server acts as an intermediary between the web server and the Python application, providing a standardized interface to ensure compatibility between different web frameworks and servers.
Python Web Server Disadvantages and Advantages
Python web servers have many advantages
- Simple and fast to implement
- Leverage Python's rich libraries
- Gentle learning curve
But there's a downside.
- Not suitable for handling large volumes of traffic
- Security settings are weak by default
Nevertheless, in the development phase or for smaller projects, a Python web server can be a great choice.
So there you have it, you've learned the basics of a Python web server and how to write CGI scripts. What do you think? It's not as hard as you think, is it? Now it's time to create your own web server.
The Python Web Server is more than just a tool - it's a powerful medium for connecting your creativity to the world. Start running a Python Web Server today. Your own web world is about to unfold!
In conclusion, the journey of web development is never-ending. Keep learning, experimenting, and growing. Who knows, your next project might surprise the world. Cheers!!!
As a side note, now that you've gotten your web server knowledge up to speed, why not learn how to create a website? Creating a Python Django Website: A Beginner's Guide Check out the post to find out!





