Run a simple Python HTTP Server

Run a simple Python HTTP Server

·

2 min read

Python HTTP Server

In this tutorial I'll show you a simple yet very easy way to run a http python server. If you haven't already go to python.org/downloads and download the latest version of python. I normally use python 3.8 or better but for those who rather stay up to date with the latest python release, you can download 3.10.0 as you wish. After you download python and the installation is complete, you then have to launch python launcher either into your ide or preferred workspace. There are other alternatives like Visual Studio Code which uses built-in plugins for any language you want to work on.
IMG_5250.jpg

Make sure you set a local path file and folder when writing code. It's best if you make a directory so that the terminal can properly fetch the destination of the file.

For this http server you don't need to write any code. You can simple start a web development page if you are new to coding. Run the following code into your terminal.

python -m http.server --cgi 8000

This will run an HTTP server on port 8000, serving the files in your current bin folder. If you properly edited the local path to this file you can always go back and edit the file. Once you learn more python code and want to further your development with frameworks, having a python http server would be the best start. If the command runs properly you should have an active directory of files serving localhost:8000

Now if you want to insert modules and string variables you write additional code. But for a first time tutorial use a simple module to print "Hello World":

from http.server import BaseHTTPRequestHandler, HTTPServer

class handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()

        message = "Hello, World!"
        self.wfile.write(bytes(message, "utf8"))
with HTTPServer(('', 8000), handler) as server:

    server.serve_forever()

This file should be saved as http.server.py. If the print is successful search more python modules and strings you want to insert into your code file. The python language has a lot of libraries and you can build a variety of different websites, statistical models, computes, games etc. Now that you created your first http server search python frameworks Django, Flask and Jinja as the main popular ones to increase your learning and web development skills. Search more tutorials on YouTube to increase your skills and use different methods to solve problems. Not all codes work the same for developers. Your job is to think the process through and solve how the developer created the site. Thats all for now.

Never Stop Coding (It's a double negative)