view whoisi_cache.py @ 6:5a9e578c80fa

changed around protocol a bit
author Atul Varma <varmaa@toolness.com>
date Thu, 31 Dec 2009 13:08:59 -0800
parents 47990d4e6df7
children 98f1da3b585c
line wrap: on
line source

MAX_PEOPLE_REQ_SIZE = 100

def split_seq(seq, size):
    """
    Split up the given sequence into pieces of the given size.

    Taken from http://code.activestate.com/recipes/425044/.
    """

    return [seq[i:i+size] for i in range(0, len(seq), size)]

class WhoisiCache(object):
    APP_NAME = "whoisi-cache"

    def __init__(self, server, storage, batch_size=MAX_PEOPLE_REQ_SIZE):
        self.server = server
        self.batch_size = batch_size
        self.people = storage

    def refresh_people(self, people_ids):
        for person_id in people_ids:
            result = self.server.get_person(self.APP_NAME, person_id + 1)
            self.people[person_id] = result['person']

    def update(self):
        pid = self.server.get_max_person_id(app=self.APP_NAME)
        interval = range(len(self.people) + 1, pid + 1)
        subintervals = split_seq(interval, self.batch_size)
        for subinterval in subintervals:
            first = subinterval[0]
            last = subinterval[-1]
            result = self.server.get_people(app=self.APP_NAME,
                                            first=first,
                                            last=last)
            for person_id in range(first, last + 1):
                self.people.append(result['people'][str(person_id)])