Python - HTTP Server


Python standard library comes with a in-built webserver which can be invoked for simple web client server communication. The port number can be assigned programmatically and the web server is accessed through this port. Though it is not a full featured web server which can parse many kinds of file, it can parse simple static html files and serve them by responding them with required response codes.

The below program starts a simple web server and opens it up at port 8001. The successful running of the server is indicated by the response code of 200 as shown in the program output.

import SimpleHTTPServer
import SocketServer

PORT = 8001

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT

When we run the above program, we get the following output −

serving at port 8001 - - [14/Jun/2018 08:34:22] "GET / HTTP/1.1" 200 -

Serving a localhost

If we decide to make the python server as a local host serving only the local host, then we can use the following programm to do that.

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

HandlerClass = SimpleHTTPRequestHandler
ServerClass  = BaseHTTPServer.HTTPServer
Protocol     = "HTTP/1.0"

if sys.argv[1:]:
    port = int(sys.argv[1])
    port = 8000
server_address = ('', port)

HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."

When we run the above program, we get the following output −

Serving HTTP on port 8000 ...

Useful Video Courses


Python Online Training

Most Popular

187 Lectures 17.5 hours

Malhar Lathkar


Python Essentials Online Training

55 Lectures 8 hours

Arnab Chakraborty


Learn Python Programming in 100 Easy Steps

136 Lectures 11 hours

In28Minutes Official


Python with Data Science

75 Lectures 13 hours

Eduonix Learning Solutions


Python 3 from scratch to become a developer in demand

70 Lectures 8.5 hours

Lets Kode It


Python Data Science basics with Numpy, Pandas and Matplotlib

63 Lectures 6 hours

Abhilash Nelson