Write a simple HTTP Server in Python

Original address : Write a simple HTTP server in Python
http://www.acmesystems.it/python_httpd
Source code in the example :
https://github.com/tanzilli/playground/tree/master/python/httpserver.

Write a simple HTTP Server in Python

Python has built-in modules that support the HTTP protocol, which can be used to develop web servers with fewer features in standalone versions. The implementation module that supports this feature in Python is BaseFTTPServer. We only need to introduce it in the project:

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
Hello world

Let's start with the first basic example It just returns "Hello World!" on the web browser
Let's take a look at the first basic example, outputting "Hello World" on a browser
Example1. py .

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
PORT_NUMBER = 8080
#This class will handles any incoming request from
#the browser 
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
  self.send_response(200)
  self.send_header('Content-type','text/html')
  self.end_headers()
  # Send the html message
  self.wfile.write("Hello World !")
  return
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()

Execute the following command to run:

Python example1. py.

Open this address in your browser http://your_ip:8080
The browser will display "Hello World!" At the same time, two log messages will appear on the terminal:

Started https server on port 8080
10.55.98.7-- [30/Jan/2012 15:40:52] "GET/HTTP/1.1" 200-
10.55.98.7-- [30/Jan/2012 15:40:52] "GET/avicon. ico HTTP/1.1" 200-.

Serve static files

Let's try providing examples of static files, such as index.xml, style.css, JavaScript, and images:

Example2. py .

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
PORT_NUMBER = 8080
#This class will handles any incoming request from
#the browser 
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
  if self.path=="/":
      self.path="/index_example2.html"
  try:
      #Check the file extension required and
      #set the right mime type
      sendReply = False
      if self.path.endswith(".html"):
          mimetype='text/html'
          sendReply = True
      if self.path.endswith(".jpg"):
          mimetype='image/jpg'
          sendReply = True
      if self.path.endswith(".gif"):
          mimetype='image/gif'
          sendReply = True
      if self.path.endswith(".js"):
          mimetype='application/javascript'
          sendReply = True
      if self.path.endswith(".css"):
          mimetype='text/css'
          sendReply = True
      if sendReply == True:
          #Open the static file requested and send it
          f = open(curdir + sep + self.path) 
          self.send_response(200)
          self.send_header('Content-type',mimetype)
          self.end_headers()
          self.wfile.write(f.read())
          f.close()
      return
  except IOError:
      self.send_error(404,'File Not Found: %s' % self.path)
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()

This new example implements the following functions:

  • Check request file extension
  • Set the correct media type and return it to the browser
  • Open the requested file
  • Send to browser

Enter the following command to run it:

Python example2. py.

Then open it in your browser http://your_ip:8080
A homepage will appear on your browser.

Read data from a form

Now explore how to read data from HTML tables.

Example3. py .

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import cgi
PORT_NUMBER = 8080
#This class will handles any incoming request from
#the browser 
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
  if self.path=="/":
      self.path="/index_example3.html"
  try:
      #Check the file extension required and
      #set the right mime type
      sendReply = False
      if self.path.endswith(".html"):
          mimetype='text/html'
          sendReply = True
      if self.path.endswith(".jpg"):
          mimetype='image/jpg'
          sendReply = True
      if self.path.endswith(".gif"):
          mimetype='image/gif'
          sendReply = True
      if self.path.endswith(".js"):
          mimetype='application/javascript'
          sendReply = True
      if self.path.endswith(".css"):
          mimetype='text/css'
          sendReply = True
      if sendReply == True:
          #Open the static file requested and send it
          f = open(curdir + sep + self.path) 
          self.send_response(200)
          self.send_header('Content-type',mimetype)
          self.end_headers()
          self.wfile.write(f.read())
          f.close()
      return
  except IOError:
      self.send_error(404,'File Not Found: %s' % self.path)
#Handler for the POST requests
def do_POST(self):
  if self.path=="/send":
      form = cgi.FieldStorage(
          fp=self.rfile, 
          headers=self.headers,
          environ={'REQUEST_METHOD':'POST',
                   'CONTENT_TYPE':self.headers['Content-Type'],
      })
      print "Your name is: %s" % form["your_name"].value
      self.send_response(200)
      self.end_headers()
      self.wfile.write("Thanks %s !" % form["your_name"].value)
      return          
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()

Run this example:

Python example3. py.

Enter your name next to the "Your name" tag.

Related articles