How to Create an HTTP Server in Python
Creating an HTTP server in Python is incredibly easy thanks to the http
module in the standard library. Specifically, we’ll be using the http.server
object to achieve this.
Quick Way to Run an HTTP Server
Before we dive into the code, let’s talk about a quick way to run an HTTP server without writing any code. Simply run the following command:
1 | python -m http.server --cgi 8000 |
This command will start an HTTP server on port 8000, serving the files from the current folder. While this server may not have all the features of Nginx or Apache, it’s often sufficient for prototypes and personal test projects.
Creating an HTTP Server Programmatically
Now, let’s use the http.server
module in Python to programmatically serve a “Hello, World!” string to anyone connecting on port 8000. Here’s the code:
1 | from http.server import BaseHTTPRequestHandler, HTTPServer |
Once you run this program locally, you can open your web browser and visit http://localhost:8000. You’ll see the “Hello, World!” string being served on that page. This code responds to GET requests for any URL with a 200 response and a Content-type: text/html
header.
Inside the do_GET
method, we write to wfile
, which is the output stream for sending the response back to the client.
Expanding the Functionality
To handle other HTTP methods, such as POST requests, you can implement additional methods like do_POST
or do_HEAD
. Here’s an example:
1 | from http.server import BaseHTTPRequestHandler, HTTPServer |
Using Web Frameworks
Python offers various web frameworks, such as Flask and Django, that can be used to build more complex applications on top of the HTTP server. These frameworks provide additional features and abstractions to simplify web development.
Tags: Python, Web server, HTTP server, programming