3 Lines of Python Code to Write A Web Server | by Christopher Tao | Towards Data Science

You must know that Python can be used to write web servers very effectively. It is known that there are many popular and excellent frameworks and libraries such as Django and Flask, which allows backend developers to focus on the business logic and save a lot of time on coding.
However, have you ever know that Python’s built-in library http.server that can also be used to write a web server? Also, do you know that you may even write one with only three lines of code? In this article, I’ll show you how to write a web server and run it in ONE minute!
The web server will need to be started somewhere, so you need to think about where you want to start it. Then, you probably want to put your code over there.
Also, we will need to import the http.server library. Optionally, it is recommended to import the os library to make sure that the webserver is indeed running in the “current” directory. In other words, using the current directory as the root path of the webserver.
import osfrom http.server import HTTPServer, CGIHTTPRequestHandler
From the http.server library, we need the HTTPServer class to instantiate the server object, as well as the CGIHTTPRequestHandler class as the request handler.
If you don’t know what is CGI, here is a brief definition from Wikipedia:
In computing, Common Gateway Interface (CGI) is an interface specification for web servers to execute programs like console applications (also called command-line interface programs) running on a server that generates web pages dynamically. Such programs are known as CGI scripts or simply as CGIs. The specifics of how the script is executed by the server are determined by the server. In the common case, a CGI script executes at the time a request is made and generates HTML.[1]
Then, let’s code the server in three lines of code, no kidding.
Let’s make sure that the server is created at the current directory and use it as the root path. os.chdir() method will set the path as the current working directory. Here we set the ., which is the current directory as its working directory.
# Make sure the server is created at current directoryos.chdir('.')
Let’s create a “server object” from the HTTPServer class. It takes two arguments, the first one is the server_address which is a tuple of
The address that listens to, where the empty string means listen to localhost
The port number that listens to. I’ll use port 80 so I don’t have to input the port number to access. It is up to you to use other port numbers such as 8080
# Create server object listening the port 80server_object = HTTPServer(server_address=('', 80), RequestHandlerClass=CGIHTTPRequestHandler)
The second argument is the request handler class. Here we use CGIHTTPRequestHandler that we have already imported.
Nothing else, let’s run it!
# Start the web serverserver_object.serve_forever()
The serve_forever() method will start the server based on the server object we have just created and make sure it is constantly running.
Here is all the code:import osfrom http.server import HTTPServer, CGIHTTPRequestHandler# Make sure the server is created at current directoryos.chdir('.')# Create server object listening the port 80server_object = HTTPServer(server_address=('', 80), RequestHandlerClass=CGIHTTPRequestHandler)# Start the web serverserver_object.serve_forever()
Save all the code into a file called pyserver.py. Then, go to the command line and run the Python script.
python pyserver.py
You will see nothing comes out in the stdout, that is expected. Go to your browser and type in localhost, the webserver is already working.
So, this web server will allow you to browse files from the root path.
Now, you may ask why I need this webserver? Right, it is not that useful. But think about what you can do with a web browser? For example, I use to download some academic research papers which are usually in PDF format. You’ll find that navigating between sub-folders and opening PDF files in a web browser is much faster than using Windows Explorer and Mac OS Finder.
Also, in this example, we’re running the web server on the local machine. If you could run this Python script on a remote machine, then you got a very quick file sharing server!
In this article, I have introduced how to use only three lines of Python code to write a web server that allows you to browse the files on the server.
However, it needs to be conscious that the http.server with such a simple implementation cannot be secure. Therefore, please do not use only these three lines of code in an important environment, which might become a security hole that potentially can be hacked.
medium.com
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
[1] Common Gateway Interface, Wikipedia https://en.wikipedia.org/wiki/Common_Gateway_Interface