The Wayback Machine - https://web.archive.org/web/20240906235928/https://www.geeksforgeeks.org/network-programming-python-http-server/
Open In App

Network Programming Python – HTTP Server

Last Updated : 24 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

HTTP Web Server is simply a process which runs on a machine and listens for incoming HTTP Requests by a specific IP and Port number, and then sends back a response for the request.

Python has a built-in webserver provided by its standard library, can be called for simple client-server communication. The http.server and socketserver are the two main functions used to create a web server. Port number can be defined manually in the program which is used to access the webserver. This web server is functional for many types of file formats, but it is not fully featured. A simple static HTML files can easily be parsed and served by responding with the required response code. A basic implementation of python HTTP web server is given below :

Sample HTML File :

<html>

   <head>

       <title>Python HTTP Server</title>

   </head>

   <body>

       <h1>Simple HTTP Server</h1>

       <p>Congratulations! The HTTP Server is working!

Welcome to GeeksForGeeks</p>

   </body>

</html>

Python3




# Import libraries
import http.server
import socketserver
  
# Defining PORT number
PORT = 8080
  
# Creating handle
Handler = http.server.SimpleHTTPRequestHandler
  
# Creating TCPServer
http = socketserver.TCPServer(("", PORT), Handler)
  
# Getting logs
print("serving at port", PORT)
http.serve_forever()


Output:

serving at port 8080
127.0.0.1 - - [17/Oct/2020 00:31:27] "GET / HTTP/1.1" 200 -



Execute the above program in the directory where the HTML File is saved. After creating the Web Server open the Web Browser and type http://localhost:8080/ in the URL. 

Here, SimpleHTTPRequestHandler is used to create a custom handler. TCPServer tells the server to send and receive messages. To invoke TCPServer, two arguments are required the TCP Address i.e. IP and PORT, and second is the handler. TCP Address is a tuple consisting of IP address and PORT number. Serve_forever() is a function of the TCPServer instance that starts the server and listens and responds to the incoming requests.

The localhost is the host machine(in our case the system we are using), used to access the network services using the loopback network interface.

If the python program is to be used only as localhost serving, the below program is used for that purpose :

Python3




# Import libraries
import sys
import http.server
import socketserver
  
# Creating handle
HandlerClass = http.server.SimpleHTTPRequestHandler
  
# Creating Server
ServerClass  = http.server.HTTPServer
  
# Defining protocol
Protocol     = "HTTP/1.0"
  
# Setting TCP Address
if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8000
server_address = ('127.0.0.1', port)
  
# invoking server
HandlerClass.protocol_version = Protocol
http = ServerClass(server_address, HandlerClass)
  
# Getting logs
sa = http.socket.getsockname()
print("Serving HTTP on", sa[0], "port", sa[1], "...")
http.serve_forever()


Output:



Similar Reads

Network Programming Python - HTTP Clients
The request from the client in HTTP protocol reaches the server and fetches some data assuming it to be a valid request. This response from the server can be analyzed by using various methods provided by the requests module. Some of the ways below provide information about the response sent from the server to the Python program running on the clien
2 min read
Network Programming Python - HTTP Requests
HTTP stands for HyperText Transfer Protocol, which works on the client-server machine. In most cases, the web browser acts as the client, and the computer which hosts the website acts as a server. Python provides the requests module to play with HTTP requests. The requests module plays a major role in HTTP requests, apart from simple request and th
2 min read
Setting up a simple HTTP server using Python
In this article, we are going to learn how to set up a simple and local HTTP server using Python. An HTTP server can be very useful for testing Android, PC or Web apps locally during development. It can also be used to share files between two devices connected over the same LAN or WLAN network. Installation On the terminal run the following stateme
2 min read
Building a basic HTTP Server from scratch in Python
In this article, we are going to learn how to set up a simple and local HTTP server using Python. An HTTP server can be very useful for testing Android, PC, or Web apps locally during development. It can also be used to share files between two devices connected over the same LAN or WLAN network. Installation: On the terminal run the following state
2 min read
How to Deploy Python WSGI Apps Using Gunicorn HTTP Server Behind Nginx
This article describes how to deploy a Python WSGI application using Gunicorn and Nginx. Before proceeding with the tutorial, it's a good idea to first familiarize yourself with the terms WSGI, Gunicorn, and Nginx. Web Server Gateway Interface or WSGI is a specification that describes how a web server (in this case Nginx) interacts with a Python we
5 min read
How To Send Files Using Python Built-In Http Server
Python's built-in HTTP server offers a straightforward way to share files over a local network or the internet without the need for complex setups. In this tutorial, we'll walk through the step-by-step process of using Python's built-in HTTP server to send files to clients. Setting Up the HTTP ServerThe first step is to start the HTTP server. Open
2 min read
Launch an HTTP Server with a Single Line of Python Code
Python, with its built-in capabilities, offers a simple and effective way to do this. With just a single line of code, you can launch an HTTP server to serve files from your local directory. This feature can be incredibly handy for developers, educators, and anyone needing a quick and easy way to share files over a network. Use Cases to Launch An H
2 min read
Python Network Programming
Python provides two levels of access to network programming. These are - Low-Level Access: At the low level, you can access the basic socket support of the operating system. You can implement client and server for both connection-oriented and connectionless protocols.High-Level Access: At the high level allows to implement protocols like HTTP, FTP,
6 min read
Telnet - Python Network programming
Telnet is a networking protocol that follows a client-server model. It uses TCP as its underlying communication protocol. It is typically used to start and a remote command-line session, typically on a server. Some facts about telnet:Uses Transmission Control Protocol for data transmission.Bi-directional 8-bit protocolThe protocol standard was init
5 min read
Network Programming in Python - DNS Look-up
Domain Name System also known as DNS is a phonebook of the internet, which has related to the domain name. DNS translates the domain names to the respective IP address so that browsers can access the resources. Python provides DNS module which is used to handle this translation of domain names to IP addresses. Finding RecordsThe dnspython module pr
4 min read
Http Request methods - Python requests
Python requests module has several built-in methods to make Http requests to specified URI using GET, POST, PUT, PATCH or HEAD requests. A Http request is meant to either retrieve data from a specified URI or to push data to a server. It works as a request-response protocol between a client and server. A web browser may be the client, and an applic
7 min read
Download a file over HTTP in Python
In this article, we are going to see how to install a File from HTTP using Python. For this we will use the following methods: Using RequestUsing urllibUsing wgetUsing requests Here we send an HTTP request to the server and save the HTTP response in a response object and received content as a .png file in binary format. C/C++ Code # imported the re
1 min read
Difference between Functional Programming and Object Oriented Programming
What is Functional Programming?In functional programming, we have to build programs using functions. An example of functional programming is Haskell language. What is Object Oriented Programming?Object-oriented programming is built by using classes and objects. In this, we have concepts of encapsulation, inheritance, polymorphism, and Data abstract
3 min read
Learn Programming Languages- List of 11 Popular Programming Languages
In this rapidly growing world, programming languages are also rapidly expanding, and it is very hard to determine the exact number of programming languages. It is an essential part of software development because it creates a communication bridge between humans and computers. Now, if you are a beginner who wants to learn, search the internet, you w
9 min read
Flask HTTP methods, handle GET &amp; POST requests
In this article, we are going to learn about how to handle GET and POST requests of the flask HTTP methods in Python. HTTP Protocol is necessary for data communication. In the context of the World Wide Web, an HTTP method is a request method that a client (e.g. a web browser) can use when making a request to a server (e.g. a web server). There are
6 min read
Tornado- HTTP servers and clients
Tornado is a Python web framework and a library for async networks. It is meant for non-blocking, highly effective apps. Tornado has become popular because it can handle large numbers of simultaneous connections easily. In this article, we will explain Tornado HTTP servers and clients. What are HTTP servers and clients?HTTP Server: An HTTP server i
4 min read
Making HTTP Requests from a FastAPI Application to an External API
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use, efficient, and reliable, making it a popular choice for developing RESTful APIs and web applications. Your FastAPI server may need to fetch data from other external APIs, to perform da
4 min read
Flask - HTTP Method
In this article, we will learn how to handle HTTP methods, such as GET and POST in Flask using Python. Here, we will understand the concept of HTTP, GET, and HTTP POST, and then we will the example and implement each in Flask. Before starting let's understand the basic terminology: GET: to request data from the server.POST: to submit data to be pro
8 min read
Difference between PUT and POST HTTP requests
Pre-Requisite: Hyper Text Transfer Protocol PUT and POST requests have lots of similarities certainly when making an HTTP request and both can be meddled with so that one performs the functions of the other. This article revolves around the major differences between PUT and POST Requests. HTTP PUT RequestHTTP PUT is a request method supported by HT
3 min read
Network Centrality Measures in a Graph using Networkx | Python
Centrality Measures allows us to pinpoint the most important nodes of a Graph. This essentially helps us to identify : Influential nodes in a Social Network. Nodes that disseminate information to many nodes Hubs in a transportation network Important pages in the Web Nodes that prevent the Network from breaking up Firstly, we need to consider the fa
6 min read
Network Scanning using scapy module - Python
Scapy is a library supported by both Python2 and Python3. It is used for interacting with the packets on the network. It has several functionalities through which we can easily forge and manipulate the packet. Through scapy module we can create different network tools like ARP Spoofer, Network Scanner, packet dumpers etc. This module can be used to
3 min read
View Computer's Important Network Information Using Python
While working in a network, we do some troubleshooting with the network or Internet problem. This time we need to check your own system network connection information. We can find the network connection in the Control Panel in Windows. The best way to find this information we can use ipconfig command in CMD. When you use ipconfig /all then you can
1 min read
Python - Network Interface
Network interface is nothing but interconnection between two hardware equipment or protocol layers in a computer network. A network interface usually has some form of the network address. It is generally a network interface card that does not have any physical existence. It can be implemented in a software interface. It is difficult to keep track o
1 min read
Access files of a devices in the same network using Python
We have so many ways to Transfer Files from one computer to another in Linux and Ubuntu but there we have to change the permissions of the Apache Folder and then Share the files. But in windows, we cannot share files using Apache so here we have discussed Python Method to Share files between Systems and Mobiles which are connected on the same netwo
2 min read
Scraping data in network traffic using Python
In this article, we will learn how to scrap data in network traffic using Python. Modules Neededselenium: Selenium is a portable framework for controlling web browser.time: This module provides various time-related functions.json: This module is required to work with JSON data.browsermobproxy: This module helps us to get the HAR file from network t
5 min read
Python Script to Monitor Network Connection and saving into Log File
In this article, we are going to see how to monitor the network connection and save the log file in Python. The basic ideology of this script is to give real-time information about if the system the script is being run on is connected to an internet connection or not, and save that information into a log file simultaneously, keeping records of when
8 min read
Network Scanner in Python
A network scanner is one major tool for analyzing the hosts that are available on the network. A network scanner is an IP scanner that is used for scanning the networks that are connected to several computers. To get the list of the available hosts on a network, there are two basic methods - ICMP Echo Request It is also known by using ‘ping command
3 min read
Implementing Artificial Neural Network training process in Python
An Artificial Neural Network (ANN) is an information processing paradigm that is inspired the brain. ANNs, like people, learn by example. An ANN is configured for a specific application, such as pattern recognition or data classification, through a learning process. Learning largely involves adjustments to the synaptic connections that exist betwee
4 min read
Merge PDF stored in Remote server using Python
Prerequisites: Working with PDF files in Python There are many libraries for manipulating PDF files in Python but all are using when that all PDF files already downloaded in your local machine. But what if your target PDF files are in Remote server, you have only URLs of files and no required download in your machine or compute server. Here We will
2 min read
PostgreSQL - Connect To PostgreSQL Database Server in Python
The psycopg database adapter is used to connect with PostgreSQL database server through python. Installing psycopg: First, use the following command line from the terminal: pip install psycopg If you have downloaded the source package into your computer, you can use the setup.py as follows: python setup.py build sudo python setup.py installCreate a
4 min read