Updated April 18, 2023
Introduction to Python HTTP Server
Python HTTP server is a kind of web server that is used to access the files over the request. Users can request any data or file over the webserver using request, and the server returns the data or file in the form of a response. The HTTP server is one of the most famous and widely used servers, and most of the websites still running on this protocol. HTTP is generally preferred for the dev servers, not for the products. Production server protocols need to be more secure. Python provides inbuilt classes to make our HTTP server with the help of that Python socket server. TCPServer has a subclass HTTPServer. It is responsible for creating requests, and it listens to HTTP sockets for handling the request.
Example of Python HTTP Server
Given below is the example of Python HTTP Server:
Let’s create a basic http web server:
from http.server import HTTPServer, BaseHTTPRequestHandler class CustomHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('content-type','text/html') self.end_headers() self.wfile.write('Python HTTP Webserver Tutorial'.encode()) def main(): PRT = 8000 srv = HTTPServer(('',PRT), CustomHandler) print('Server started on port %s' %PRT) srv.serve_forever() if __name__ == '__main__': main()
Server started on port 8000
127.0.0.1 – – [28/May/2020 20:36:48] “GET / HTTP/1.1” 200 –
127.0.0.1 – – [28/May/2020 20:36:48] “GET /favicon.ico HTTP/1.1” 200 –
In the above example, we have imported HTTPServer from http.server module and BaseHTTPRequestHandler class from the same module. HTTPServer is going to handle all requests like get requests or post requests. We have created a method CustomHandler.Now we have defined our main method, and here we are gonna serve our actual server. We have created a variable PRT that will hold our port number. You can define any port number that must be free. Then we created another variable, srv that is holding the instance of the HTTPServer. It takes two parameters; the first parameter is a tuple of hostname and port number. We are running it on localhost so we can leave it empty and port number. The second parameter will be the request handler.
We have defined ‘CustomHandler’ as our request handler. Then we have simply printed a message that will indicate that our server is up and running. Now we have defined the server.serve_forever method. This will start the server, and it will keep running until we don’t stop it.
Now we have created a ‘CustomHandler’ that will be used to handle all requests that the server receives. We have defined BaseHTTPRequestHandler into the class; it will inherit all the properties of the base request class. Now we have created the do_GET method that takes self as an argument and service should send back a response and the status codes like 200, and it means the file which we are looking on the server is found and will be displayed on the web page. ‘self.send_header’ is responsible for sending the headers information like content type like HTML Page. We also have to close the headers once we have listed them.
Now we will put some content that will load once the server is running. ‘self.wfile.write’ is responsible for writing to the file. We are using encode method because http servers cannot send string on the http request, so encoding the string into bias is served on the web page.
if __name__ == ‘__main__’: this means that this file is running directly and we haven’t imported it. So now we can execute this program, python will execute the main method, and we can use our port number and localhost in the browser to check if our server is running or not. “localhost:8000”use this address in the url bar and hit enter. You might see the message that you have written along with the port number which we have defined.
Now you can change the output message, but you won’t be able to see the change if we refresh. We need to stop the server and execute the program again.
We are using BaseHTTPRequestHandler for creating our server.
We have the following instance variables.
- client_address: It is a tuple that refers to a client address containing hostname and port.
- close_connection: It is a boolean value that is set before the handle_one_request(); it indicates whether another request is being created or the current connection is closed.
- path: It contains the path of the request.
- headers: It is used to hold the instance of the file that is created by the message class. This instance is responsible for parsing the HTTP Request.
- wfile: It is responsible for writing the stream to the client-side. The proper HTTP protocol is followed for achieving successfully writing to http clients.
- protocal_version: It tells the version of the HTTP Protocol. If the permission is HTTP/1.1, then the server will allow persistent http connections. It is important to mention the length of the content in all request responses to the client.
This is a guide to Python HTTP Server. Here we discuss the introduction to Python HTTP Server along with example respectively. You may also have a look at the following articles to learn more –