[Tutor] BaseHTTPServer Tutorial

Karthik Gurumurthy karthikg@aztec.soft.net
Mon, 31 Dec 2001 10:10:43 +0530


core python programming has this code..s'd be helpful.
in the beginning ,place a plain test.html file in the directory from where
you start the server and
try accesing it through

http://localhost/test.html

wffile in BaseHTTPRequestHandler points to the output stream where we can
write.
this code just reads the contents of the file u tried accessing
("test.html")
and writes it to that stream which can be seen on the browser.

...code...

from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        try:
            f = open(curdir + sep + self.path) #self.path has /test.html
            self.send_response(200)
            self.send_header('Content-type',	'text/html')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)

def main():
    try:
        server = HTTPServer(('', 80), MyHandler)
        print 'Welcome to the machine...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()

if __name__ == '__main__':
    main()

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Ross Wolfson
Sent: Sunday, December 30, 2001 9:26 AM
To: tutor@python.org
Subject: [Tutor] BaseHTTPServer Tutorial


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()



_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor