#!/Library/Frameworks/Python.framework/Versions/Current/bin/python # Q-13 MCS 275 The 22 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 a regular file with name '/tmp/data????' # where ???? are four random digits. # For every request made by a browser, one line with the current time # of the request is written to file and the user sees in the browser # window the content of this file. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from random import randint from time import ctime r = randint(1000,9999) name = '/tmp/data' + str(r) f = open(name,'w') f.close() class WebServer(BaseHTTPRequestHandler): """ Web server to count number of visits to a site. """ def do_GET(self): """ Says welcome to first time connecting client. """ f = open(name,'a') f.write(ctime() + '\n') f.close() f = open(name,'r') L = f.readlines() f.close() for s in L: self.wfile.write(s + '\n') 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()