-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathadd_participant.py
314 lines (255 loc) · 9.13 KB
/
add_participant.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import boto3
import time
import datetime
import re
import json
from boto3.dynamodb.conditions import Key
dynamodb = boto3.resource('dynamodb')
responseHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials' : True }
def get_current_poll_id(second_attempt = False):
"""Tries 2 times to access the config table and takes the current poll id.
Parameters:
second_attempt: Flag for the second attempt.
Returns:
Current poll id.
"""
config_table = dynamodb.Table('fp.config')
try:
response = config_table.get_item(
Key={
'id': 'CurrentPoll'
}
)
except Exception:
if second_attempt:
raise Exception('Database error!')
# tries again if the first attempt failed
time.sleep(1)
return get_current_poll_id(True)
return int(response['Item']['value'])
def get_item_polls_max(poll_id, second_attempt = False):
"""Tries 2 times to access the polls table and takes the max attribute.
Parameters:
poll_id: Current poll id.
second_attempt: Flag for the second attempt.
Returns:
Max attribute from the current poll.
"""
polls_table = dynamodb.Table('fp.polls')
try:
response = polls_table.get_item(
Key={
'id': poll_id
}
)
except Exception:
if second_attempt:
raise Exception('Database error!')
# tries again if the first attempt failed
time.sleep(1)
return get_item_polls_max(poll_id, True)
return response['Item']['max']
def query_participants(poll_id, last_evaluated_key = None, second_attempt = False):
"""Query the participants table and returns all results for given poll, if the first attempt failed or has unprocessed keys tries again.
Parameters:
last_evaluated_key: Last evaluated key, if some data is not read.
second_attempt: Flag for the second attempt.
Returns:
List with participants.
"""
result = []
participants_table = dynamodb.Table('fp.participants')
try:
if last_evaluated_key:
response = participants_table.query(
KeyConditionExpression=Key('poll').eq(poll_id),
ConsistentRead=True,
ExclusiveStartKey=last_evaluated_key
)
else:
response = participants_table.query(
KeyConditionExpression=Key('poll').eq(poll_id),
ConsistentRead=True
)
except Exception:
if second_attempt:
raise Exception('Database error!')
# tries again if the first attempt failed
time.sleep(1)
return query_participants(poll_id, last_evaluated_key, True)
if 'Items' in response:
result = response['Items']
if (not second_attempt) and ('LastEvaluatedKey' in response):
# tries again if there are unprocessed keys
try:
time.sleep(1)
second_result = query_participants(poll_id, response['LastEvaluatedKey'], True)
except Exception:
raise Exception('Database error!')
result.append(second_result)
return result
def put_item_participants(item, second_attempt = False):
"""Tries 2 times to put the participant in the participants table.
Parameters:
item: Item with attributes of the participants table (poll, added, person, friend).
second_attempt: Flag for the second attempt.
Returns:
Max attribute from the current poll.
"""
participants_table = dynamodb.Table('fp.participants')
try:
participants_table.put_item(
Item=item
)
except Exception:
if second_attempt:
raise Exception('Database error!')
# tries again if the first attempt failed
time.sleep(1)
return put_item_participants(item, True)
return {
'statusCode': 200,
'headers': responseHeaders,
'body': json.dumps({ 'added': item['added'] })
}
def add_participant(event, context):
"""Adds a participant into the current poll.
Returns:
Status of adding.
"""
if event['body'] is None:
return {
'statusCode': 400,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'No request body!'})
}
try:
requestBody = json.loads(event['body'])
except:
return {
'statusCode': 400,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'Bad request body!'})
}
if type(requestBody) != dict:
return {
'statusCode': 400,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'Bad request body!'})
}
if 'person' not in requestBody:
return {
'statusCode': 400,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'person parameter doesn\'t exist in the API call!'})
}
# lower letters and remove all unnecessary whitespaces
person = ' '.join(requestBody['person'].lower().split())
friend = '/'
if 'friend' in requestBody:
friend = ' '.join(requestBody['friend'].lower().split())
if len(person) < 3:
return {
'statusCode': 400,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'Person name should contains at least 3 letters!'})
}
if len(person) > 25:
return {
'statusCode': 400,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'Too long person name!'})
}
if len(friend) == 0:
return {
'statusCode': 400,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'Friend name should contains at least 1 letter!'})
}
if len(friend) > 25:
return {
'statusCode': 400,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'Too long friend name!'})
}
# person allowed characters - lower letters (mac cyrilic, eng latin), digits, whitespace between characters
mac_alphabet = 'абвгдѓежзѕијклљмнњопрстќуфхцчџш'
search_not_allowed = '[^a-z0-9 ' + mac_alphabet + ' ]'
if re.search(search_not_allowed, person):
return {
'statusCode': 400,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'person value contains not allowed characters!'})
}
# friend allowed characters - lower letters (mac cyrilic, eng latin), digits, +, whitespace between characters
search_not_allowed = search_not_allowed[:-1] + '+]'
if (friend != '/') and re.search(search_not_allowed, friend):
return {
'statusCode': 400,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'friend value contains not allowed characters!'})
}
# get current poll id
try:
current_poll_id = get_current_poll_id()
except Exception:
return {
'statusCode': 500,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'Database error!'})
}
# get max participants
polls_table = dynamodb.Table('fp.polls')
try:
current_poll = polls_table.get_item(
Key={
'id': current_poll_id
}
)
except Exception:
return {
'statusCode': 500,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'Database error!'})
}
max_participants = current_poll['Item']['max']
# query participants
try:
participants = query_participants(current_poll_id)
except Exception:
return {
'statusCode': 500,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'Database error!'})
}
if len(participants) == max_participants:
return {
'statusCode': 400,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'No more participants in this poll!'})
}
# check for duplicate
if friend == '/':
for participant in participants:
if (participant['person'] == person) and (participant['friend'] == '/'):
return {
'statusCode': 400,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'Participant ' + person + ' exists in the current poll!'})
}
# add the participant
added = int(datetime.datetime.now().timestamp() * 1000)
try:
put_status = put_item_participants({
'poll': current_poll_id,
'added': added,
'person': person,
'friend': friend
})
except Exception:
return {
'statusCode': 500,
'headers': responseHeaders,
'body': json.dumps({'errorMessage': 'Database error!'})
}
return put_status