#!/Library/Frameworks/Python.framework/Versions/Current/bin/python # Q-13 MCS 275 Tue 20 Apr 2010 : quiz13a.py # Give code to set up a web server that can handle an indefinite number # of requests and shuts down when the user presses ctrl+c. # Web browsers connect to the server via http://localhost:8888/. # The server maintains an anydbm file with name '/tmp/data????' # where ???? are four random digits. # The anydbm file has one field 'count' that stores the total number of # requests handled by the server. # For every request made by a browser, the user sees in the browser # window the message "welcome, visitor n" where n is zero for the first # visitor and 1 for the second visitor, etc. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import anydbm from random import randint r = randint(1000,9999) f = '/tmp/data' + str(r) d = anydbm.open(f,'c') d['count'] = '0' class WebServer(BaseHTTPRequestHandler): """ Web server to count number of visits to a site. """ def do_GET(self): """ Says welcome to first time connecting client. """ n = d['count'] self.wfile.write("welcome, visitor " + n) d['count'] = str(int(n) + 1) def main(): """ Starts up the server. """ try: ws = HTTPServer(('',8888),WebServer) print 'welcome to our web server' print 'press ctrl c to stop server' ws.serve_forever() except KeyboardInterrupt: print ' ctrl c pressed, shutting down' ws.socket.close() main()