Python HTTP Server

Python HTTP Server
Techiio-author
Written by Sagar RabidasDecember 20, 2021
12 min read
Python
4 VIEWS 1 LIKES 0 DISLIKES SHARE
1 LIKES 0 DISLIKES 4 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

In this blog, we will discuss the Python HTTP Server.

Python:-

Python is a widely-used, interpreted, object-oriented, and high-level programming language with dynamic semantics, used for general-purpose programming. It was created by Guido van Rossum, and first released on February 20, 1991.

While you may know python as a large snake, the name of the Python programming language comes from an old BBC television comedy sketch series called Monty Python’s Flying Circus.

One of the amazing features of Python is the fact that it is one person’s work. Usually, new programming languages are developed and published by large companies employing lots of professionals, and due to copyright rules, it is very hard to name any of the people involved in the project. Python is an exception.

Of course, van Rossum did not develop and evolve all the Python components himself. The speed with which Python has spread around the world is a result of the continuous work of thousands (very often anonymous) programmers, testers, users (many of them aren’t IT specialists), and enthusiasts, but it must be said that the very first idea (the seed from which Python sprouted) came to one head – Guido’s.

blogpost

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.

blogpost

Example of Python HTTP Server

Given below is the example of a Python HTTP Server:

Let's create a basic HTTP web server:

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 a Python HTTP Server:

Let's create a basic HTTP web server:

Code:

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()
Output:

The 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 –

blogpost

Inside the above instance, we have imported an HTTP server from HTTP. Server module and Base HTTP request handler magnificence from the identical module. Httpserver goes to deal with all requests like getting requests or publish requests. We've got created a way custom handler. Now we've got defined our principal method, and right here we're gonna serve our actual server. We've got created a variable part a good way to preserve our port number. You could define any port quantity that ought to be unfastened. Then we created another variable, SRV that is keeping the instance of the HTTP server. It takes parameters; the primary parameter is a tuple of hostname and port quantity. We're walking it on localhost so we can depart it empty and port quantity. The second parameter could be the request handler.

We've defined ‘custom handler’ as our request handler. Then we have truly printed a message to imply that our server is up and running. Now we have described the server.Serve_forever method. This can begin the server, and it will preserve going for walks 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.while.write’ is responsible for writing to the file. We are using encode method because HTTP servers cannot send strings 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.
  • while: 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.
Python
Python HTTP Server
CPython
4 VIEWS 1 LIKES 0 DISLIKES SHARE
1 LIKES 0 DISLIKES 4 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance