Python web server example demonstrating a custom server implementation using Python code
Python web server example demonstrating a custom server implementation using Python code

Set Up a Web Server with Python: Built-in & Custom Methods

Python provides straightforward ways to set up a web server, whether you need a quick solution or a more customized approach. You can launch a basic web server with a single command, or build a custom server to handle specific functionalities. This article will guide you through both methods for creating a web server using Python. These servers can be accessed on your local network, including localhost and other network hosts, and can even be made accessible across locations using a VPN.

Utilizing Python’s Built-in Web Server

For quickly sharing files or testing web content, Python has a built-in web server module. Starting this server is incredibly simple.

Simple Command to Start Server

Execute the following command in your terminal:

python3 -m http.server

This command immediately starts a web server on port 8080. You can access it by opening your web browser and navigating to http://127.0.0.1:8080/.

The server is also accessible to other devices on your local network using your machine’s IP address (typically in the format 192.168.-.-). By default, this server allows you to download files from the directory where you launched the command, making it a convenient tool for local file sharing.

Creating a Custom Web Server in Python

For applications requiring specific behaviors or more control over server functionality, you can create a custom web server using Python. This involves leveraging Python’s HTTP libraries to define how the server handles requests.

Code Example and Explanation

Below is an example of a basic custom web server in Python. This server will respond to GET requests and display a simple webpage.

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("<title>https://pythonbasics.org</title>", "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>", "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.")

Save this code to a Python file (e.g., custom_web_server.py) and run it. Like the built-in server, it will be accessible on port 8080. When you access a URL like http://127.0.0.1:8080/example, the do_GET() method in the MyServer class is executed.

Python web server example demonstrating a custom server implementation using Python codePython web server example demonstrating a custom server implementation using Python code

In this code, self.path captures the requested URL path from the browser (e.g., /example in the example URL). The server responds with a basic HTML page constructed within the do_GET method. This demonstrates the fundamental structure for handling GET requests in a custom Python web server.

Conclusion

Python simplifies the process of setting up web servers, offering both a quick built-in option and the flexibility to create custom servers. Whether you need a simple file server or a foundation for a more complex web application, Python provides the necessary tools to get started quickly.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *