How to Create a Python Web Server

-

Affiliate Disclosure: Every purchase made through our affiliate links earns us a pro-rated commission without any additional cost to you. Here are more details about our affiliate disclosure.

This article is about you to learn to Create a Python Web Server. A webserver in Python can be set up in two ways. Python supports a webserver out of the box. You can start a web server with a one-liner.

However, you can also create a custom web server with unique functionality. In this article, you will learn how to do that.

The web server in this example can be accessed on your local network only. This can either be a localhost or another network host. You could serve it cross-location with a VPN.

Create a Python Web Server

Example

Builtin webserver

To start a webserver, run the command below:

python3 -m http.server

That will open a webserver on port 8080. You can then open your browser at http://127.0.0.1:8080/

The webserver is also accessible over the network using your 192.168.-.- address.

This is a default server that you can use to download files from the machine.

Webserver

Run the code below to start a custom web server. We need to use the HTTP protocol to create a custom web server.

By design, the HTTP protocol has a “get” request which returns a file on the server. If the file is found, it will return 200.

The server will start at port 8080 and accept default web browser requests.

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

hostName = "localhost"
serverPort = 8080

class MyServer(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://pythonbasics.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), MyServer)
    print("Server started http://%s:%s" % (hostName, serverPort))

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass

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

If you open an URL like http://127.0.0.1/example, the method do_GET() is called. We send the webpage manually in this method.

The variable self.path returns the web browser URL requested. In this case, it would be /example.

Related Articles

Like our Article/ Blog? Can buy a Buttermilk for our team.. Click here

Pardeep Patelhttps://pardeeppatel.com/
Hi!, I am Pardeep Patel, an Indian passport holder, Traveler, Blogger, Story Writer. I completed my M-Tech (Computer Science) in 2016. I love to travel, eat different foods from various cuisines, experience different cultures, make new friends and meet other.

Share this article

-- Advertisement --

LEAVE A REPLY

Please enter your comment!
Please enter your name here

-- Advertisement --