Python SimpleHTTPServer with Default and Custom Paths

Python provides us with a very basic yet useful server tool named simplehttpserver for serving files on localhost. It can be of great use for learning web development as the server is one of the easiest to set up. In this article, we will discuss the basics of python simplehttpserver, its advantages, and disadvantages.

What is Python SimpleHTTPServer?

Python SimpleHTTPServer is a simple and easy-to-use HTTP server tool written in Python. It is primarily used for serving static files, such as HTML, CSS, JavaScript, and images. It can also be used to create dynamic web pages, using Python as the server-side scripting language.

SimpleHTTPServer is a great tool for quickly setting up a web server for testing and development purposes. It is easy to set up and use and requires minimal configuration. 

Set up SimpleHTTPServer on Your Machine 

Set up SimpleHTTPServer on your machine , you can open a terminal window and navigate to the directory that contains the files you wish to serve on the server. Then, type the following command: 

python -m SimpleHTTPServer [port] 

Here, [port] is the port number you want the server to listen on. By default, SimpleHTTPServer will use port 8000. Once the server is running, you can access the files in your directory by visiting http://localhost:[port]/ in your web browser. For example, if the server is running on port 8000, you can visit http://localhost:8000/ to access the files. 

The above syntax doesn’t work in Python3. For python3, you can use the following syntax.

python -m http.server [port]

Run Python SimpleHTTPServer on 8000 Port Using the Command Line

To run python SimpleHTTPServer on 8000 port using the command line, you can type the following command in the command prompt on your windows or Linux machine.

python -m SimpleHTTPServer 8000

The above command works only in python 2. If you have python 3 installed on your system, executing the above command will lead to an error saying “No module named SimpleHTTPServer”. This is due to the reason that the SimpleHTTPServer has been renamed to http.server module in python 3. Hence, to run SimpleHTTPServer on 8000 port in python 3 using the command line, you can use the following command.

python -m http.server 8000

After executing the above command, the SimpleHTTPServer is started in the current working directory. You can observe this in the following image.

simplehttpserver example

After starting the server in the command line, If you open the localhost server at the designated port, you can see all the files in the current working directory.

simplehttpserver example

You can click on any filename shown in the browser to issue a GET request to the server. After clicking on the file name, the text and HTML files will be opened in your browser window itself. Those files that cannot be opened in the browser will get downloaded through your browser.

Run Python SimpleHTTPServer on a Custom Port Using the Command Prompt

The port number 8000 is the default for SimpleHTTPServer. To use a custom port to run SimpleHTTPServer on your machine, you can specify the port number as shown below.

simplehttpserver example

In the above image, you can observe that the server has been started on port 8112. You can use the port number to open the files in the browser as shown in the following output.

 example

In the browser, you can click on each file to view it in the browser. Each time you click on a file, it sends a get request to the SimpleHTTPServer. You can observe this in the terminal where you are running the server. 

 example

In the above image, you can observe that the SimpleHTTPServer received the GET request when we clicked on the avidpy.txt file. Once the server serves the request, the file is shown in the browser.

Browser Output:

 example

In the above approaches, when we need to close the server and type CTRL+C, the program runs into an exception and then stops as shown in the following example.

 example

To avoid the clutter above, we can implement an exception handler to close the program when it is interrupted.

For this, Instead of directly starting the server using the command line, you can write a python script to run SimpleHTTPServer on your windows or Linux machine. For this, we first need to write a python script to start the server as shown below.

import http.server
import socketserver

PORT = 8000

handler = http.server.SimpleHTTPRequestHandler
server=socketserver.TCPServer(("", PORT), handler)
print("Server started at port 8000. Press CTRL+C to close the server.")
try:
	server.serve_forever()
except KeyboardInterrupt:
	server.server_close()
	print("Server Closed")	

The above program, when run in the terminal, first creates a SimpleHTTPRequestHandler. Then, it creates a TCPServer and starts the server to serve the requests. If the program is interrupted using the keyboard and it runs into the KeyboardInterrupt exception, it handles the exception and closes the server using the server_close() method. You can observe this in the following image.

simplehttpserver example

In the above examples, you can observe that the system is using the original file names to send the GET request in the SimpleHTTPServer. Then, the files are served to the browser by the server. Here, the browser is a client. Hence, it is possible that the browser or any other client doesn’t know the name of the file, or the file isn’t shown in the client interface. Also, the client is able to see all the files on the server. This is not a desired situation. We can serve a custom page to the client using a custom path for this.

Serve File Using a Custom Path in Python SimpleHTTPServer

To serve a file using a custom path in SimpleHTTPServer, we will implement a custom request handler named MyHttpRequestHandler with a custom do_GET() method.

The do_GET() method receives the paths sent in the GET requests and maps them to the files that we want to serve using the paths. After this, whenever the client gives a custom path, the file mapped to the corresponding path is served to the client.

import http.server
import socketserver

class CustomHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.path = 'avidpy.html'
        if self.path == '/give_me_text':
            self.path = 'avidpy.txt'
        return http.server.SimpleHTTPRequestHandler.do_GET(self)
PORT = 8000

handler = CustomHttpRequestHandler
server=socketserver.TCPServer(("", PORT), handler)
print("Server started at port 8000. Press CTRL+C to close the server.")
try:
	server.serve_forever()
except KeyboardInterrupt:
	server.server_close()
	print("Server Closed")	

Terminal output:

simplehttpserver example

Now, when we start the server, it looks as follows.

simplehttpserver example

Here, you can observe that the home page shows the HTML page instead of the files in the system. This is because of the reason that we have mapped the “/” path to the ‘avidpy.html’ file. Hence, whenever the server is started, the ‘avidpy.html’ will be served instead of showing all the files in the current working directory.

You can also serve files using other custom paths. For instance, we can serve the text file “avidpy.txt” using a custom path “give_me_text” as shown below.

simplehttpserver example

In the code, you can observe that we have mapped the “/give_me_text” path to the “avidpy.txt” file. Hence, whenever the GET request is sent on “/give_me_text”, the text file is served to the client.

Advantages of Python SimpleHTTPServer 

  1. Python SimpleHTTPServer is a simple, easy-to-use web server that can be used to serve static content, such as HTML, CSS, JavaScript, and media files.  It can be started from the command line, making it easy to quickly test web pages. It also supports CGI scripts, allowing dynamic content to be served. 
  2. Python SimpleHTTPServer is written in Python, making it easy to extend and customize. It is cross-platform, meaning that it can be run on Windows, Mac, and Linux. As you can observe, we customized the server for handling custom path names in this article.
  3. Python SimpleHTTPServer is open source, so it is free to use for any purpose. You don’t have to pay anything to anyone for this.
  4. SimpleHTTPServer supports HTTP/1.1, allowing for the efficient transfer of data. 
  5. Python SimpleHTTPServer is easy to set up and configure, fast and efficient, with minimal resource usage.

Disadvantages of Python SimpleHTTPServer 

  1. Python SimpleHTTPServer is not secure at all and can easily be exploited by malicious users. It only supports basic HTTP requests and cannot be used for more complex tasks. 
  2. SimpleHTTPServer is not suitable for high-traffic websites due to its lack of scalability. It can only serve static HTML pages and cannot be used to serve dynamic content efficiently.
  3. Python SimpleHTTPServer does not support authentication or authorization. It does not have any built-in logging capabilities. 
  4. Python SimpleHTTPServer cannot be used to serve large files effectively.  It is not suitable for providing a consistent user experience across different browsers and devices. 
  5. Python SimpleHTTPServer is not suitable for developing complex web applications. It does not support modern web technologies, such as HTML5 and CSS3.

Conclusion

SimpleHTTPServer is great for quickly setting up a lightweight web server, but it’s important to note that it is not suitable for production use. It is not secure and does not have many features, so it should only be used for testing and development. If you’re looking for a more robust web server, you may want to consider using a more feature-rich web server, such as Apache or Nginx.

I hope you enjoyed reading this article. To learn more about python programming, you can read this article on command line arguments in Python. You might also like this article on Python Indexing.

Donate to Avid Python

Dear reader,
If you found this article helpful and informative, I would greatly appreciate your support in keeping this blog running by making a donation. Your contributions help us continue creating valuable content for you and others who come across my blog. 
No matter how big or small, every donation is a way of saying "thank you" and shows that you value the time and effort we put into writing these articles. If you feel that our article has provided value to you, We would be grateful for any amount you choose to donate. 
Thank you for your support! 
Best regards, 
Aditya
Founder

If you want to Pay Using UPI, you can also scan the following QR code.

Payment QR Code
Payment QR Code

Leave a Reply