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.
Read Also
1. How to Install PIP for Python on Windows
2. Create a Classic Tic-Tac-Toe Game in Python, Download Source Code
3. Create a Notepad using Python, Download Source Code
4. Create Fruit Ninja Game in Python, Download Source Code
5. Create School Management System in Python, Download Source Code