def getCounter(self, key): # initialise counter try: f = open(self.counter_file, 'r+') self._counters = Unpickler(f).load() except: f = open(self.counter_file, 'w+') self._counters = {} f.close() if not self._counters.has_key(key): self._counters[key] = 0 return self._counters[key]
class IDRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def run(self): try: self.counter_file = os.environ.get('counter') self.get_id() except: self.send_response(400) self.send_header('Content-Type', 'text/html') self.end_headers() raise do_GET = run # do_POST = run def getCounter(self, key): # initialise counter try: f = open(self.counter_file, 'r+') self._counters = Unpickler(f).load() except: f = open(self.counter_file, 'w+') self._counters = {} f.close() if not self._counters.has_key(key): self._counters[key] = 0 return self._counters[key] def setCounter(self, key, count): self._counters[key] = count f = open(self.counter_file, 'r+') p = Pickler(f) p.dump(self._counters) f.close() def get_id(self): batch_size = None command = self.command.lower() if command == 'get' and self.path.find('?') != -1: key, qs = self.path.split('?', 1) data = cgi.parse_qs(qs) try: batch_size = int(data['batch_size'][0]) except: batch_size = None else: key = self.path # POST (also works .. let's GET for now .. ) # elif command == 'post': # key = self.path # length = self.headers.getheader('content-length') # if length: # length = int(length) # qs = self.rfile.read(length) # data = cgi.parse_qs(qs) prev_count = self.getCounter(key) next_count = prev_count + 1 if batch_size: last_count = prev_count + batch_size else: last_count = next_count self.setCounter(key, last_count) self.send_response(200) self.send_header('Content-Type', 'text/plain') self.end_headers() self.wfile.write(str(next_count))