Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.
Table of Contents
Python remains one of the best programming languages to learn in 2022, with applications in back-end web development, machine learning, scientific modelling, system operations, and several enterprise-specific software. It is generally considered one of the more approachable programming languages, with dynamically typed, English-like syntax and many libraries.
That accessibility extends to creating a Python web server, which you can do in only a few lines of code. Like our other Python tutorials, you’ll find that some of the most fundamental operations are carried out in a matter of minutes.
We’ll show you how to create your own Python web server for local testing. The whole process takes only a few minutes and a few lines of code.
But first, let’s go over what a web server is.
What is a Web Server? [Definition]
In the infrastructure of the internet, the server is one part of the client-server model. When a client browser visits a web page, it makes an HTTP request to the server containing the files needed to operate a website. The server listens to the client’s request, processes it, and responds with the required files to present the web page. This content could be HTML (the text and media you see on a website) and JSON (applications).
You might have encountered a few server error codes in your time browsing the internet - “file not found” or 404 being a more popular one. In these cases, the server has trouble accessing certain files. With a 404 error, the particular file is missing.
There are more nuances to web servers, including classification into static and dynamic web servers. For example, static web servers only return files as they are, with no extra processing. Dynamic web servers introduce databases and application servers, which you can proceed to once you’ve got the hang of static servers.
Having said all that, we should get into how you create a web server. We’ll assume you’re running the latest version of Python. There are resources for you to learn how to run a python script, among other useful lessons.
How Do You Create a Simple Python Web Server?
Launching a Python web server is quick and straightforward, and it’ll only take a few minutes for you to get up and to run. All it takes is one line of code to get the simplest of local servers running on your computer.
By local testing, your system becomes the server to the client that is your browser, and the files are stored locally on your system. The module you’ll be using to create a web server is Python’s http server. There is one caveat to this: it can only be used as a static file server. You’ll need a Python web framework, like Django, to run dynamic web servers.
Let’s get to the code, which looks like this follows:
python -m http.server
Type this into the terminal or command prompt, depending on your system, and you should see a “server started” message and a “server stopped” when you close the server.
And there you have it - your first Python webserver! Admittedly, it’s a simple one, doing nothing more than opening up a web server on your system’s default port of 8000. The port can also be changed by specifying the port number at the end of the line, like this:
python -m http.server 8080
A simple web server like the one you’ve just created is all well and good. It’s far more interesting and educational, however, to create a custom web server. After all, the best way to learn python is through a hands-on approach - code, debug, fix, rinse and repeat.
Recommend Python Course
Creating a Custom Web Server Using Python
A custom web server allows you to do more than a built-in web server. The code you’re about to see will teach you a lot about some important functions and processes. Don’t be put off by the length of the code - there are only a handful of key concepts at play here. You don’t have to manually type all of this out to test it yourself - but note the significance of those concepts.
from http.server import HTTPServer, BaseHTTPRequestHandler #Python’s built-in library
hostName = "localhost"
serverPort = 8080 #You can choose any available port; by default, it is 8000
def do_GET(self): //the do_GET method is inherited from BaseHTTPRequestHandler
self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("<p>This is an example web server.</p>", "utf-8"))
if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort)) #Server starts
webServer.server_close() #Executes when you hit a keyboard interrupt, closing the server
Before we jump into the critical parts, let’s quickly go over a few things. If you’ve done your HTML homework, then you’ll see some familiar terms in the code. The class MyServer writes to the output stream (wfile) that’s sent as a response to the client using “self.wfile.write()”. What we’re doing here is writing an elementary HTML page on the fly.
We’ll address some of the more important executions going on here, namely:
- The module http.server
- The classes HTTPServer and BaseHTTPRequestHandler, derived from the library http.server
- The do_GET method
The HTTP server is a standard module in the Python library that has the classes used in client-server communication. Those two classes are HTTPServer and BaseHTTPRequestHandler. The latter accesses the server through the former. HTTPServer stores the server address as instance variables, while BaseHTTPRequestHandler calls methods to handle the requests.
To sum up, the code starts at the main function. Next, the class MyServer is called, and the BaseHTTPRequestHandler calls the do_GET() method to meet requests. When you interrupt the program, the server closes.
If you did this correctly, you should see messages like this:
Why would you want to use a custom web server? It lets you use more methods, like do_HEAD() and do_POST(), offering additional functionality. In any case, you can see that creating a custom web server is also fairly straightforward.
It doesn’t take much to get your web server going using Python. It’s the fundamental idea that you should absorb. Creating your server is a small but significant step forward on your path to creating full-stack applications.
Try the code yourself, and perhaps even search for Python projects incorporating server implementation. There are many projects available that make use of this concept, so it’s good to know how to implement it in a larger context.
Lastly, if you’re looking for more such lessons, head over to our Python tutorials page, there’s a lot of information on everything from the best resources to lessons that focus on a specific concept.
People are also reading: