"""Components to handle access codes. """ import grok from random import SystemRandom as random from waeup.sirp.accesscodes.interfaces import IAccessCode, IAccessCodeBatch class AccessCode(grok.Model): grok.implements(IAccessCode) def __init__(self, batch_serial, batch_prefix, batch_num, random_num, cost, invalidation_date=None, student_id=None): self.batch_serial = batch_serial self.batch_prefix = batch_prefix.upper() self.batch_num = str(batch_num) self.random_num = random_num self.cost = cost self.invalidation_date = invalidation_date self.student_id = student_id @property def representation(self): return '%s-%s-%s' % ( self.batch_prefix, self.batch_num, self.random_num) class AccessCodeBatch(object): """A batch of access codes. """ grok.implements(IAccessCodeBatch) def __init__(self, creation_date, creator, batch_num, batch_prefix, cost, entry_num): self.creation_date = creation_date self.creator = creator self.batch_num = batch_num self.batch_prefix = batch_prefix self.cost = cost self.entry_num = entry_num self._used = [] def __iter__(self): if len(self._used) >= self.entry_num: for num in range(self.entry_num): random_num = self._used[num] ac = AccessCode(len(self._used), self.batch_prefix, self.batch_num, random_num, self.cost) yield ac else: while len(self._used) < self.entry_num: random_num = self.getNewRandomNum() ac = AccessCode(len(self._used), self.batch_prefix, self.batch_num, random_num, self.cost) self._used.append(random_num) yield ac def getNewRandomNum(self): """Create a random number of 10 digits. The number is returned as string. """ result = '' while result == '' or result in self._used: result = '' for x in range(10): result += str(random().randint(0, 9)) return result