1 | """Components to handle access codes. |
---|
2 | """ |
---|
3 | import grok |
---|
4 | from random import SystemRandom as random |
---|
5 | from waeup.sirp.interfaces import IWAeUPSIRPPluggable |
---|
6 | from waeup.sirp.accesscodes.interfaces import IAccessCode, IAccessCodeBatch |
---|
7 | |
---|
8 | class AccessCode(grok.Model): |
---|
9 | grok.implements(IAccessCode) |
---|
10 | |
---|
11 | def __init__(self, batch_serial, batch_prefix, batch_num, random_num, |
---|
12 | cost, invalidation_date=None, student_id=None): |
---|
13 | self.batch_serial = batch_serial |
---|
14 | self.batch_prefix = batch_prefix.upper() |
---|
15 | self.batch_num = str(batch_num) |
---|
16 | self.random_num = random_num |
---|
17 | self.cost = cost |
---|
18 | self.invalidation_date = invalidation_date |
---|
19 | self.student_id = student_id |
---|
20 | |
---|
21 | @property |
---|
22 | def representation(self): |
---|
23 | return '%s-%s-%s' % ( |
---|
24 | self.batch_prefix, self.batch_num, self.random_num) |
---|
25 | |
---|
26 | |
---|
27 | class AccessCodeBatch(object): |
---|
28 | """A batch of access codes. |
---|
29 | """ |
---|
30 | grok.implements(IAccessCodeBatch) |
---|
31 | |
---|
32 | def __init__(self, creation_date, creator, batch_num, batch_prefix, cost, |
---|
33 | entry_num): |
---|
34 | self.creation_date = creation_date |
---|
35 | self.creator = creator |
---|
36 | self.batch_num = batch_num |
---|
37 | self.batch_prefix = batch_prefix |
---|
38 | self.cost = cost |
---|
39 | self.entry_num = entry_num |
---|
40 | self._used = [] |
---|
41 | |
---|
42 | def __iter__(self): |
---|
43 | if len(self._used) >= self.entry_num: |
---|
44 | for num in range(self.entry_num): |
---|
45 | random_num = self._used[num] |
---|
46 | ac = AccessCode(len(self._used), self.batch_prefix, |
---|
47 | self.batch_num, random_num, self.cost) |
---|
48 | yield ac |
---|
49 | else: |
---|
50 | while len(self._used) < self.entry_num: |
---|
51 | random_num = self.getNewRandomNum() |
---|
52 | ac = AccessCode(len(self._used), self.batch_prefix, |
---|
53 | self.batch_num, random_num, self.cost) |
---|
54 | self._used.append(random_num) |
---|
55 | yield ac |
---|
56 | |
---|
57 | def getNewRandomNum(self): |
---|
58 | """Create a random number of 10 digits. |
---|
59 | |
---|
60 | The number is returned as string. |
---|
61 | """ |
---|
62 | result = '' |
---|
63 | while result == '' or result in self._used: |
---|
64 | result = '' |
---|
65 | for x in range(10): |
---|
66 | result += str(random().randint(0, 9)) |
---|
67 | return result |
---|
68 | |
---|
69 | class AccessCodeContainer(grok.Container): |
---|
70 | pass |
---|
71 | |
---|
72 | class AccessCodePlugin(grok.GlobalUtility): |
---|
73 | grok.name('accesscodes') |
---|
74 | grok.implements(IWAeUPSIRPPluggable) |
---|
75 | |
---|
76 | def setup(self, site, name, logger): |
---|
77 | pass |
---|
78 | |
---|
79 | def update(self, site, name, logger): |
---|
80 | pass |
---|