How to Create Python Web Server



In this article, you will learn how to create Python web server.

How to create Python web server

To create a Python web server, you can use the built-in http.server module. This module provides basic HTTP server capabilities, including serving static files and generating dynamic content using CGI scripts.

Here are the steps to create a Python web server using the http.server module:

Open a new Python file in your text editor of choice and import the http.server module:
import http.server
import socketserver
Define the port number and the directory to serve:
PORT = 8000
DIRECTORY = 'path/to/directory'

Replace “path/to/directory” with the absolute path of the directory you want to serve.

Create a new request handler by subclassing the http.server.SimpleHTTPRequestHandler class:
class MyHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.send_header('Content-type', 'text/html')
        self.wfile.write(b'Hello, world!')

In this example, the request handler responds to every GET request with a “Hello, world!” message.

Create a new socket server and start serving:
with socketserver.TCPServer(("", PORT), MyHandler) as httpd:
    print("serving at port", PORT)

This code creates a new TCP server that listens on the specified port and serves the directory using the MyHandler request handler. The serve_forever() method starts the server and runs indefinitely.

Save the file as and run it from the command line:

You should see a message that says “serving at port 8000”. Open a web browser and go to http://localhost:8000 to test the server.

Note that this example is a simple demonstration of how to create a basic Python web server. In practice, you would likely want to customize the request handler to serve more complex content or handle different types of HTTP requests. Additionally, this approach is not suitable for production use, as it provides only basic security and scalability features. For production use, you should consider using a more robust web framework, such as Flask or Django.