0% found this document useful (0 votes)
17 views11 pages

Python Simple HTTP Server Tutorial

Uploaded by

Menberu Munye
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views11 pages

Python Simple HTTP Server Tutorial

Uploaded by

Menberu Munye
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Simple HTTP

Server : A Simple HTTP


Web Server With Python
September 11, 2018 by Gulsanober Saba
Hi everyone this is a Python Simple HTTP Server Tutorial.
Here we will learn how to create HTTP server in
[Link] web server in python is very easy, just a
couple lines of code. So let’s begin.

But before proceeding next, let’s give a quick look on web


server.

What Is Web Server


Overview
 A web server is actually a network application,
running on some machine, listening on some port.
 Web server is a computer where web contents are
stored.
 A web server serves web pages to clients across the
internet or an intranet .
 It hosts the pages, scripts, programs and
multimedia files and serve them using HTTP, a
protocol designed to send files to web browsers.
 Apache web server, IIS web server, Nginx web
server, Light Speed web server etc are the
common examples of web servers.
Features
 Large data storage support
 Bandwidth controlling to regulate network traffic
 Site analysis
Types
There are two types of web servers –

 Dedicated web servers : In this, one web server


is dedicated to a single [Link] is suitable for
websites with more web traffics.
 Shared web servers : In this, a web server is
assigned to many clients and it shared among all
the clients.
How Web Server Works?
This figure clearly depicts the working principle of Web
servers.

Let’s take a close look on its working –

 For eg. a user wants to see a website like


([Link]), the user type in the url the
page using a client program(web browsers) but
before this they need to physically connected i.e.,
the computer of the user and the web server, that’s
the job of Internet. Using the TCP/IP suite of
protocol, it establishes the connection using a
combination of cable media and wireless media.
 When the connection is establishes, the client sends
a request called an http message and because the
HTTP is a connectionless protocol, the clients
disconnects from the server waiting for the
response.
 The server on the other side process the requests,
prepare the response, establishes the connection
again and send back to response.
 Again inform a HTTP message to the client when the
two computer is completely disconnect, that is the
big general.
HTTP Protocol
The most important part of a web server is HTTP [Link]
now we will see what exactly this is –

 It stands for Hyper Text Transfer Protocol.


 It is an application layer protocol that allows web
based applications to communicate and exchange
data.
 The HTTP is the messenger of web.
 The computer that communicate via the HTTP must
speak the HTTP protocol.
 It is a TCP/IP based protocol.
 It is used to deliver contents, for eg. images, audios,
videos, documents etc.
 Using HTTP is the most convenient way to quickly
and reliably move data on the web.
Example of an HTTP Message
Python Simple HTTP Server
Tutorial
Python actually comes with an built-in library just for creating
a web server. Creating web server in python is very-very
simple with just a couple lines of code. So let’s start –

Creating a New Project


In your python IDE create a new project and inside this
project create a python file like that –
Creating HTML file
First of all create an HTML file –

1
2 <!DOCTYPE html>
3 <html>
4 <head>
5 <meta charset="utf-8">
6 <title>Hello world!</title>
7 </head>
8 <body>
9 <h1>Index page!</h1>
1 <p>What Is Web Server
0
1 A web server is actually a network application, running on some machine,
1 listening on some port.
1 Web server is a computer where web contents are stored.
2 A web server serves web pages to clients across the internet or an intranet .
1 It hosts the pages, scripts, programs and multimedia files and serve them using
3 HTTP, a protocol designed to send files to web browsers.
1 </p>
4 </body>
1 </html>
5
1
6
1
7
1
8
1
9

Importing Modules
Python provides built-in [Link] module so we need not to
install any module using pip install.

[Link] Module
 [Link] is a python module which allow us to
create web server.
 By using [Link], we can make any directory
that you choose as your web server directory.
Importing Class
We have to import two
class HTTPServer and BaseHTTPRequestHandler. So
write the following codes.
1
2from [Link] import HTTPServer, BaseHTTPRequestHandler
3
 HTTPServeris a [Link] subclass. It
creates and listens at the HTTP socket, dispatching
the requests to a handler.
 BaseHTTPRequestHandler is used to handle the
HTTP requests that arrive at the server. By itself, it
cannot respond to any actual HTTP requests; it
must be subclassed to handle each request method
(e.g. GET or POST).BaseHTTPRequestHandler provides a
number of class and instance variables, and
methods for use by subclasses.
Creating a Server Holder Class
Now we need to create a class that holds the server. Give the
class name web_server or anything you like. We
pass BaseHTTPRequestHandler as a argument to this
class that inherits the message from
BaseHTTPRequestHandler.

Inside this class write the following code –

1
2 class web_server(BaseHTTPRequestHandler):
3
4 def do_GET(self):
5 if [Link] == '/':
6 [Link] = '/[Link]'
7 try:
8 #Reading the file
9 file_to_open = open([Link][1:]).read()
1 self.send_response(200)
0 except:
1 file_to_open = "File not found"
1 self.send_response(404)
1
2 self.end_headers()
1 [Link](bytes(file_to_open, 'utf-8'))
3
1
4
1
5
1
6
1
7
What We Did?
 First of all we defined a method do_GET(). This
method runs when you send GET request. And
anytime you go to a webpage in web-browser and
type the address of that webpage, you sending
a GET request to the server.
 [Link] == ‘/’ check the path of the request. We
check if its a ‘/’ that means they are on the index
page.
 And if we run the index page, [Link] =
‘/[Link]’ is the path for our [Link] page.
 The next thing we have done is that we try to read
the file that user trying to access.
 If the reading of file is successful then the try block
ends successfully.
 So if the requested file is found then we send
a 200 response. 200 response is response every
webpage sends whenever you access a page
successfully.
 Now inside the except block, we just print a
message that file not found and this will execute
whenever a user requests an invalid webpage.
 When file not find we just send a response 404 that
means the file is not found.
 Then we have to
send self.end_headers() message that is required
by the BaseHTTPRequestHandler class. It sends a
blank line, indicating the end of the HTTP headers in
the response.
 And finally we write the context of a file on the
screen. So to write on screen we have to converted
the bytes so all over file we coded using UTF-8 so
we converted the text into byte using the byte()
method.
Creating HTTP Variable
Now finally we create a HTTP variable that instance of HTTP
damon which is just call a program that runs on backend
because that typically how web service run. Write the
following code –

1
2httpd = HTTPServer(('localhost', 8080), web_server)
3httpd.serve_forever()
4
 Call HTTPServer class that python already
implemented it for us.
 We pass localhost i.e., the address of our computer
and the port on which we listen. And finally pass
the web_server class which is we have created.
 Then finally run the serve_forever() method.
It Handle requests until an
explicit shutdown() request. Poll for shutdown
every poll_interval seconds. Ignores
the timeout attribute. If you need to do periodic
tasks, do them in another thread.
Finally we have completed coding part successfully and now
we will see its execution.

Now go to your browser and type [Link] in


the [Link] this way we get the following output –

And now inside our terminal we see a 200 response has been
sended.
Congratulations we have successfully created our own simple
HTTP web server and it is working perfectly.

So friends this was all about the Python Simple HTTP


Server Tutorial. If you have any doubt or facing any trouble
dealing with this post then your comments are [Link]
yes you can share this post with python [Link]

Common questions

Powered by AI

To set up a simple HTTP server using Python’s http.server module, one needs to first create a Python project and an HTML file as content . Then, the HTTPServer and BaseHTTPRequestHandler classes must be imported . A server class derived from BaseHTTPRequestHandler should be implemented with request handling methods like `do_GET()` . Finally, an instance of HTTPServer is created by specifying the address, port, and handler, and `serve_forever()` is called to start the server .

The BaseHTTPRequestHandler class requires subclassing to handle specific HTTP request methods such as GET or POST . The `do_GET()` method is one example, which is used to respond to GET requests . In the `do_GET()` method, the server checks the request path and, if necessary, defaults it to an index page . It reads the requested file, returning a 200 response upon success or a 404 response if the file is not found . Such methods enable customization for processing different types of HTTP requests effectively .

The HTTP protocol is central to web server operations as it is the primary means by which data is transferred between the server and clients on the web . It defines the structure of request and response messages, enabling communication between web applications . By supporting the transfer of various types of content, HTTP facilitates the delivery of multimedia elements and interactive experiences to users . Additionally, its integration with the TCP/IP protocol suite ensures reliable data transmission .

HTTP, standing for Hyper Text Transfer Protocol, is an application layer protocol that enables data exchange between web-based applications . It operates over TCP/IP, allowing content delivery such as images, videos, and documents . HTTP is connectionless, meaning each request from a client is treated independently, which simplifies communication but can impact caching and session management . It is the most convenient and reliable way to move data between systems on the web .

In a production environment, using a simple HTTP server from Python’s http.server module can pose several challenges such as lack of scalability, since it is designed for small-scale development and testing rather than handling high traffic loads . It lacks advanced features such as SSL support for secure connections, efficient load balancing, and request handling optimizations which are necessary for robust production environments . Also, the connectionless nature of HTTP can complicate session management and data security .

The built-in http.server module in Python provides a simple and straightforward way to set up an HTTP server without the need to install additional packages, which simplifies initial setup . It allows any directory to be turned into a web server directory, offering flexibility to developers . Additionally, its use in educational contexts is beneficial for learning fundamental web server concepts without the complexities of a full-stack web server setup .

When a client wants to access a website, it sends an HTTP request message to the server after a physical connection is established over the internet using the TCP/IP suite . The HTTP protocol is connectionless, so the client disconnects from the server while waiting for a response . The server then processes the request, prepares a response, re-establishes a connection, and sends the response back to the client . Finally, the disconnect occurs again once the response is delivered .

To implement a GET request handler in a Python Simple HTTP Server, one defines the `do_GET()` method within a class derived from BaseHTTPRequestHandler . This method checks if the request path points to the index page and reads the requested file from server storage. If successful, a 200 response is sent; otherwise, a 404 error is returned . Such a simple server setup is beneficial for educational purposes, helping learners understand the basic mechanics of handling web requests, error management, and response generation, without the overhead of complex server configurations .

The Python Simple HTTP Server handles file requests via the `do_GET()` method in the BaseHTTPRequestHandler class, which checks the request path and attempts to read the corresponding file . If the requested file is found, it sends a 200 response; if not, a 404 error response is sent . Any exceptions during file reading trigger the except block, which handles the error by returning a 'File not found' message to the client .

Dedicated web servers are used by a single user, ideal for websites with high traffic, as they provide the resources exclusively to one client, enhancing performance and reliability . In contrast, shared web servers host multiple clients, sharing resources among all, which can be more cost-effective but may lead to reduced performance under high load conditions due to resource competition .

You might also like