-
Notifications
You must be signed in to change notification settings - Fork 0
/
post_classroom.py
189 lines (158 loc) · 5.51 KB
/
post_classroom.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
#VIA API
__author__ = 'Randal'
import boto3
import os
import json
def handler(event, context):
print("Event Initial: "+str(event))
if 'body' in event:
# Si el evento se llama desde apigateway(Lambda Proxy), el evento original vendra en el body
# Y nos los quedaremos. Si no, usamos el evento original ya que traera todos los datos
event = json.loads(event['body'])
print("Event took(Body): "+str(event))
if 'class' in event:
classs = event["class"]
else:
return return_error(400, "Class not inserted")
if 'level' in event:
level = event["level"]
else:
return return_error(400, "Level not inserted")
is_valid_class, message = is_valid_classroom(event["class"], event["level"])
if not is_valid_class:
print ("Class not valid format")
return return_error(400, message)
if exist_classroom(classs, level):
print("The class already exist")
return return_error(409, "The class already exist")
return create_classroom(classs, level)
def create_classroom(classs, level):
response, path = create_folder_in_bucket(classs, level)
if response['ResponseMetadata']['HTTPStatusCode'] is not 200:
print("Bucket creation: Failed")
return return_error(response['ResponseMetadata']['HTTPStatusCode'], "Error creating the folder in s3 \n"+response['ResponseMetadata'])
response = create_topic(classs, level)
if response['ResponseMetadata']['HTTPStatusCode'] is not 200:
print("Topic creation: Failed")
rollback(s3=True, path=path, sns=False)
return return_error(response['ResponseMetadata']['HTTPStatusCode'], "Error creating the topic. Rollback executed\n"+response['ResponseMetadata'])
arn_topic = response['TopicArn']
response = insert_in_dynamodb(classs, level, path, arn_topic)
if response['ResponseMetadata']['HTTPStatusCode'] is not 200:
print("DynamoDB creation: Failed")
rollback(s3=True, path=path, sns=True, topic=arn_topic)
return return_error(response['ResponseMetadata']['HTTPStatusCode'], "Error Inserting in Dynamo DB. Rollback executed \n"+response['ResponseMetadata'])
response_to_return = {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin" : "*"
},
"body": "Classroom created correctly with a folder in "+path+" and SNS Topic "+arn_topic
}
#return "Classroom created correctly with a foler in "+path+" and SNS Topic "+arn_topic
return response_to_return
def rollback(s3, path, sns, topic=None):
if s3:
delete_folder_in_s3(path)
if sns:
delete_topic(topic)
def delete_folder_in_s3(path):
client = boto3.client('s3')
response1 = client.delete_object(
Bucket=os.environ['originalBucket'],
Key=path
)
response2 = client.delete_object(
Bucket=os.environ['resizedBucket'],
Key=path
)
return response1, response2
def delete_topic(arn):
client = boto3.client('sns')
response = client.delete_topic(
TopicArn=arn
)
return response
def insert_in_dynamodb(classs, level, path_s3, arn_topic):
client = boto3.client('dynamodb')
response = client.put_item(
TableName=os.environ['tableClassroom'],
Item={
'Class':{
'S': classs
},
'Level':{
'S': level
},
'Folder':{
'S': path_s3
},
'Topic':{
'S': arn_topic
}
}
)
return response
def is_valid_classroom(classs, level):
if level not in ["ESO", "Infantil", "Primaria", "Bachillerato"]:
return False, "The Level should be 'Infantil', 'Primaria', 'ESO' or 'Bechillerato'"
try:
classs = int(classs[0])
except Exception:
return False, "The class must have the format: 1A, 2B, 3C..."
return True, "The format of class is valid"
def exist_classroom(classs, level):
client = boto3.client('dynamodb')
response = client.scan(
TableName=os.environ['tableClassroom'],
Select='ALL_ATTRIBUTES',
ScanFilter={
'Class': {
'AttributeValueList':[{
'S': classs
}
],
'ComparisonOperator': 'EQ'
},
'Level': {
'AttributeValueList':[{
'S': level
}
],
'ComparisonOperator': 'EQ'
}
}
)
return response["Count"] > 0
def create_folder_in_bucket(classs, level):
client = boto3.client('s3')
path = 'Classrooms/'+level+'/'+classs+'/'
response = client.put_object(
Bucket=os.environ['originalBucket'],
Body='',
Key=path
)
if response['ResponseMetadata']['HTTPStatusCode'] is not 200:
return response
response = client.put_object(
Bucket=os.environ['resizedBucket'],
Body='',
Key=path
)
return response, path
def create_topic(classs, level):
client = boto3.client('sns')
topic_name = classs+level
response = client.create_topic(
Name=topic_name
)
return response
def return_error(statusCode, message):
response = {
"statusCode": statusCode,
"headers":{
"Access-Control-Allow-Origin" : "*"
},
"body": message
}
return response