The BaseHTTPServer Module

This is a basic framework for HTTP servers, built on top of the SocketServer framework.

Example 7-36 generates a random message each time you reload the page. The path variable contains the current URL, which you can use to generate different contents for different URLs (as it stands, the script returns an error page for anything but the root path).

Example 7-36. Using the BaseHTTPServer Module


import BaseHTTPServer
import cgi, random, sys

 "That's as maybe, it's still a frog.",
 "Albatross! Albatross! Albatross!",
 "It's Wolfgang Amadeus Mozart.",
 "A pink form from Reading.",
 "Hello people, and welcome to 'It's a Tree.'"
 "I simply stare at the brick and it goes to sleep.",

class Handler(BaseHTTPServer.BaseHTTPRequestHandler):

 def do_GET(self):
 if self.path != "/":
 self.send_error(404, "File not found")
 self.send_header("Content-type", "text/html")
 # redirect stdout to client
 stdout = sys.stdout
 sys.stdout = self.wfile
 sys.stdout = stdout # restore
 def makepage(self):
 # generate a random message
 tagline = random.choice(MESSAGES)
 print "

" print "

" print "

Today's quote: " print "%s" % cgi.escape(tagline) print "" print "" PORT = 8000 httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler) print "serving at port", PORT httpd.serve_forever()

See the SimpleHTTPServer and CGIHTTPServer modules for more extensive HTTP frameworks.

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols


Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules

Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh © 2008-2020.
If you may any questions please contact us: