-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathguestbook.py
337 lines (239 loc) · 7.63 KB
/
guestbook.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import base64
import json
import uuid
from flask import Flask
from flask import request
app = Flask(__name__)
##-- Route Methods --##
@app.route('/guests/', methods=['GET', 'POST'])
def process_guests():
"""Processes guests requests.
Performs processing for the REST requests or access to the guests
collection resource.
Args:
N/A; there are no method parameters.
However, for POST requests, it is expected that the FORM field "guest"
will contain JSON-formatted new-guest information:
{
"name": "Wilkins Distilled",
"age": "16",
"photo": ""
}
Returns:
For GET request, JSON formatted list of guest information is returned:
{
"1231238080AAA":
{
"id": "1231238080AAA",
"name": "Wilkins Distilled",
"age": "16",
"photo": ""
},
"1123ABCD099DF":
{
"id": "1123ABCD099DF",
"name": "Xperia Phone",
"age": "26",
"photo": ""
}
}
The photo field will hold base64encoded contents.
For POST requests, operations status is returned:
{
"result": "success"
}
The result field will either have a value of "success" or "fail".
Raises:
N/A
"""
method = request.method
output = ''
if method == 'GET':
output = process_guests_fetch(request)
elif method == 'POST':
output = process_guests_add(request)
if output == None:
output = ''
return output
@app.route('/guests/<guest_id>', methods=['GET'])
def process_guest(guest_id):
"""Processes fetch single guest requests.
Performs processing for the REST requests for a single guest entry from the
guests collection resource.
Args:
N/A; there are no method parameters.
Returns:
If the id is a valud guest entry ID, JSON formatted guest information:
{
"name": "Wilkins Distilled",
"age": "16",
"photo": ""
}
The photo field will hold base64encoded contents.
Raises:
N/A
"""
output = process_guests_fetch(request, guest_id)
if output == None:
output = ''
return output
##-- Non-Route Methods --##
def process_guests_fetch(request ,guest_id = None):
"""Processes guests listing requests.
Performs processing for listing requests for the guests collection resource.
Args:
request: web request object
Returns:
If no id value is specified, JSON formatted list of guest information:
{
"1231238080AAA":
{
"id": "1231238080AAA",
"name": "Wilkins Distilled",
"age": "16",
"photo": ""
},
"1123ABCD099DF":
{
"id": "1123ABCD099DF",
"name": "Xperia Phone",
"age": "26",
"photo": ""
}
}
If a valid guest ID is specified, JSON-formatted guest information
{
"id": "1231238080AAA",
"name": "Wilkins Distilled",
"age": "16",
"photo": ""
}
Note: The photo field will hold base64encoded contents.
"""
guests = load_guests_data();
data = None
if guest_id != None and len(guest_id.strip()) > 0:
if guests.has_key(guest_id):
data = guests[guest_id]
if data == None:
data = guests
data = json.dumps(data)
return data
def process_guests_add(request):
"""Processes guests add requests.
Performs processing for addition or modification requests for the guests
collection resource.
Args:
request: web request object
The request object' form attribute is checked for the field "guest"
to contain JSON-formatted new-guest information:
{
"name": "Wilkins Distilled",
"age": "16",
"photo": ""
}
Returns:
Operation result in a JSON-formatted structure:
{
"result": "success"
}
The result field will either have a value of "success" or "fail".
"""
resp = create_response('fail')
# Check if there is guest info passed
if request.form == None or len(request.form['guest']) == 0:
resp['reason'] = 'no_data'
return json.dumps(resp)
# Fetch guest info and use as JSON data
argInfo = request.form['guest']
try:
argInfo = argInfo.strip()
argInfo = json.loads(argInfo)
except:
resp['reason'] = 'invalid_data'
return json.dumps(resp)
guests = load_guests_data()
guestInfo = None
# Check if guest ID exists (update-mode)
if argInfo.has_key('id'):
guestId = argInfo['id']
if guests.has_key(guestId):
guestInfo = guests[guestId]
# If not update mode
if guestInfo == None:
#print guests
# Traverse guest list and compare against submitted data
for key, guest in guests.iteritems():
# If name matches, consider as update-mode
if guest['name'] == argInfo['name']:
#print guest
#print argInfo
guestId = guest['id']
guestInfo = argInfo
break
# Check if it's a new entry
if guestInfo == None:
guestId = str(uuid.uuid4())
guestInfo = argInfo
guestInfo['id'] = guestId
guests[guestId] = guestInfo
try:
save_guests_data(guests)
resp['result'] = 'success'
resp['id'] = guestId
except:
resp['reason'] = 'failed_saving'
return json.dumps(resp)
def load_guests_data():
"""Loads guests data.
Reads/deserializes JSON object from the JSON file, guests.json.
Args:
N/A
Returns:
N/A
Raises:
Exception when loading fails
"""
data = None
try:
with open('guests.json') as datafile:
data = json.load(datafile)
except:
data = None
if data == None:
data = json.loads('{}')
return data
def save_guests_data(guests):
"""Saves guests data.
Saves/serializes the specified guests data to a file, guests.json.
Args:
guests: guests information to be saved
Returns:
N/A
Raises:
Exception when saving fails
"""
with open('guests.json', 'w') as datafile:
json.dump(guests, datafile)
def create_response(result):
"""Creates response data.
Creates a JSON object intended to be used as response data.
Args:
result: string to be the value of the result field
Returns:
For POST requests, operations status is returned:
{
"result": "success"
}
Raises:
N/A
"""
obj = json.loads("""
{
"result": "success"
}
""")
obj["result"] = result
return obj
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')