A webserver in Python can be setup in two ways. Python supports a webserver out of the box. You can start a web server with a one liner.
But you can also create a custom web server which has unique functionality. In this article you'll learn how to do that.
The web server in this example can be accessed on your local network only. This can either be localhost or another network host. You could serve it cross location with a vpn.
Related course: Complete Python Programming Course & Exercises
Example
Builtin webserver
To start a webserver run the command below:
1
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.
Web server
Run the code below to start a custom web server. To create a custom web server, we need to use the HTTP protocol.
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.
1 |
# Python 3 server example |
If you open an url like http://127.0.0.1:8080/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