How to setup simple Python HTTP server in Linux


Gaming Laptop Series

An HTTP server can be very useful for learning, local development, and testing web or mobile applications. Python provides inbuilt classes that you can use to make your own HTTP server. The HTTPServer which is a subclass of TCPServer in Python is responsible for creating requests and listening to HTTP sockets for handling the request.

In this article, I will discuss how to set up a simple Python HTTP server in Linux.

Prerequisites

To follow this guide you should have –

Setting up Python HTTP server

In two ways you can set up a simple HTTP server in Python. It comes with a built-in HTTP server that can be started with a single command.

OR you can also create a custom web server with unique functionality that you can access locally or remotely.

Start Python built-in web server

Open your terminal and use the given command to run the built HTTP server –

python3 -m http.server

OR

python -m  http.server

On executing this command you will see the given output in your terminal.

http server

Now open your browser and enter the given URL –

http://localhost:8080

This will display the list of files and directories of your current working directory.

local host http server

Creating a custom HTTP server

The following code shows the example of creating a custom HTTP server in Python. You can add unique functionalities to it.

# Python 3 HTTP server example
from http.server import BaseHTTPRequestHandler, HTTPServer
import time

hostName = "localhost"
serverPort = 8080

class MyHttpServer(BaseHTTPRequestHandler):
     def do_GET(self):
          self.send_response(200)
          self.send_header("Content-type", "text/html")
          self.end_headers()
          self.wfile.write(bytes("<html><head><title>https://cyanogenmods.org</title></head>", "utf-8"))
          self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
          self.wfile.write(bytes("<body>", "utf-8"))
          self.wfile.write(bytes("<p>This is an example web server.</p>", "utf-8"))
          self.wfile.write(bytes("</body></html>", "utf-8"))

if __name__ == "__main__":
     webServer = HTTPServer((hostName, serverPort), MyHttpServer)
     print("Server started http://%s:%s" % (hostName, serverPort))

     try:
        webServer.serve_forever()
     except KeyboardInterrupt:
        pass

    webServer.server_close()
    print("Server stopped.")

 

When you execute this code you will see the given output in your terminal –

code output

You can verify the working of the web server by entering the given URL in your browser –

http://localhost:8080

You will see the given page in your web browser.

browser ouput

Conclusion

So you have successfully created and opened the HTTP server in Python. Now if you have a query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.