[Tutor] BaseHTTPServer Tutorial

Ross Wolfson RWolfson@home.com
Sat, 29 Dec 2001 22:55:55 -0500


Does anyone know of a good BaseHTTPServer tutorial? It seems like a great
library since Edna (http://edna.sourceforge.net) was written using it, but I
wonder how they learned how to use it. I've tried google and I can't get any
real tutorials on BaseHTTPServer. (One showing how to make a simple 'hello
world' webpage might be nice). Ednas source is also way too complex for a
simple hello world to come from it. (I also don't know anything about http
programming and headers etc)

-Ross W.








P.S. - Heres my nonworking source to a hello world attempt(don't try to
execute it, it doesn't work)(To be safe, I included every library edna did,
and I also copied a lot of source)


import SocketServer
import BaseHTTPServer
import ConfigParser
import sys
import string
import os
import cgi
import urllib
import socket
import re
import stat
import random
import time
import struct


# determine which mixin to use: prefer threading, fall back to forking.
try:
  import thread
  mixin = SocketServer.ThreadingMixIn
except ImportError:
  if not hasattr(os, 'fork'):
    print "ERROR: your platform does not support threading OR forking."
    sys.exit(1)
  mixin = SocketServer.ForkingMixIn



class myserver(mixin,BaseHTTPServer.HTTPServer):
    def __init__(self):
        self.port=80
        SocketServer.TCPServer.__init__(self,('',
self.port),myrequesthandler)
    def server_bind(self):
        # set SO_REUSEADDR (if available on this platform)
        if hasattr(socket, 'SOL_SOCKET') and hasattr(socket,
'SO_REUSEADDR'):
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
1)
            BaseHTTPServer.HTTPServer.server_bind(self)
    """
    def acl_ok(self, ipaddr):
        if not self.acls:
            return 1
        ipaddr = dot2int(ipaddr)
        for allowed, mask in self.acls:
            if (ipaddr & mask) == (allowed & mask):
                return 1
        return 0
    """

class myrequesthandler(BaseHTTPServer.BaseHTTPRequestHandler):

  def do_GET(self):
    self._perform_GET()

  def _perform_GET(self):
    if not self.server.acl_ok(self.client_address[0]):
      self.send_error(403, 'Forbidden')
      return
    path = self.translate_path()
    if path is None:
      self.send_error(400, 'Illegal URL construction')
      return
    self.send_response(200)
    self.send_header("Content-Type", 'text/html')
    self.end_headers()
    self.wfile.write('<html><head><title>Testing</title></head><body>Testing
1 2 3...')
    self.wfile.write('<br><br><br>')
    self.wfile.write(`self.client_address[0]`)

    print self.client_address[0]




if __name__ == '__main__':
  print 'working!'
  svr=myserver()
  svr.serve_forever()