-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
474 lines (378 loc) · 12.5 KB
/
app.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
"""First API, local access only"""
import hug
import os
import redis
import json
import base64
from xmlrpc.client import Binary
import uuid
import random
from datetime import datetime
from datetime import timedelta\
from falcon import HTTP_400
# try:
# REDIS_URL = redis.from_url(os.environ.get("REDIS_URL"))
# except:
REDIS_URL = "redis://h:p5fb02a20cc28b27ca3b002543e7266b49df0ab1273719499c89a26d52f959d60@ec2-34-206-56-227.compute-1.amazonaws.com:52639"
demo_logins = {
'username' : 'shelter',
'password' : '1234'
}
user_db_id = 0
pet_db_id = 1
user = redis.from_url(REDIS_URL, db=user_db_id)
pet = redis.from_url(REDIS_URL, db=pet_db_id)
super_secret_key = 'abcd1234'
"""
HELPER FUNCTIONS
"""
def get_uuid():
return str(uuid.uuid4())
#login authentication
authentication = hug.http(requires=hug.authentication.basic(hug.authentication.verify('shelter', '1234')))
@authentication.get('/login')
@authentication.post('/login')
def login(user: hug.directives.user, key=super_secret_key):
return {"message": "Successfully authenticated with user: {0}".format(user),
"key" : key}
def cors_support(response, *args, **kwargs):
response.set_header('Access-Control-Allow-Origin', '*')
response.set_header('Access-Control-Allow-Method', 'POST, GET, OPTIONS')
response.set_header('Access-Control-Allow-Headers', 'Content-Type')
@hug.options('/link', requires=cors_support)
def options_link():
return
@hug.options('/document', requires=cors_support)
def options_document():
return
@hug.options('/pet', requires=cors_support)
def options_pet():
return
@hug.options('/owner', requires=cors_support)
def options_owner():
return
@hug.options('/breeds', requires=cors_support)
def options_breeds():
return
@hug.options('/reminder', requires=cors_support)
def options_reminder():
return
@hug.options('/image_for_pet', requires=cors_support)
def options_image_for_pet():
return
"""
USER ROUTES
"""
@hug.post('/owner', requires=cors_support)
def create_owner(body, response):
if body.get('username', None) is None:
response.status = HTTP_400
return {"message" : "Bad person, you need a username"}
username = body.get('username', None)
if body.get('role', None) is None:
body['role'] = "owner"
role = body['role']
first_name = body.get('firstName', '')
last_name = body.get('lastName', '')
body['adopted_pets'] = []
body['owner_id'] = '{}:{}:{}:{}'.format(role, first_name, last_name, username)
#post owner to owner redis database
user.set(body['owner_id'], json.dumps(body))
return body
def get_owner_keys():
owners = [Id.decode("utf-8") for Id in user.keys() if 'owner' in Id.decode("utf-8")]
return owners
@hug.get('/owner', requires=cors_support)
def get_owner(owner_id: hug.types.text = None):
# get owner from user redis database
if owner_id is None:
# get all user record keys
return get_owner_keys()
else:
# return user record
return json.loads(user.get(owner_id))
@hug.get('/owner_by_username', requires=cors_support)
def get_owner_by_username(response, username: hug.types.text = None):
owner_keys = get_owner_keys()
username_keys = [key for key in owner_keys if username in key]
if len(username_keys) == 1:
username_key = username_keys[0]
return json.loads(user.get(username_key))
# return username_key
elif len(username_keys) == 0:
response.status = HTTP_400
return {
"message": "No key with username exists or multiple people with same username."
}
"""
PET ROUTES
"""
@hug.post('/pet', requires=cors_support)
def create_pet(body):
pet_uuid = get_uuid()
pet_name = body.get('name', None)
temp_key = '{}:{}'.format(pet_name, pet_uuid)
body['adopted'] = False
static_reminders = [
{
'pet_id' : temp_key,
'description' : 'Rabies shot due',
'timestamp' : str(datetime.now() + timedelta(days=4))
},
{
'pet_id' : temp_key,
'description' : 'Vet checkup',
'timestamp' : str(datetime.now() + timedelta(days=30))
}
]
body['reminders'] = static_reminders
#put doc_ids on pet
body['documents'] = get_document_ids()
body['pet_id'] = temp_key
breed = body.get('breed', None)
body['image'] = get_random_image_path_for_breed(breed)
#post pet to pet redis database
pet.set(temp_key, json.dumps(body))
return body
@hug.get('/pet', requires=cors_support)
def get_pet(pet_id: hug.types.text = None):
# get pet from user redis database
if pet_id is None:
# get all pet records
return pet.keys()
else:
return json.loads(pet.get(pet_id))
"""
LINKING ROUTES
"""
@hug.post('/link', requires=cors_support)
def link_owner_pet(body):
pet_id = body['pet_id']
owner_id = body['owner_id']
#get and alter owner dict
owner_object = json.loads(user.get(owner_id))
adopted_pet_list = owner_object.get('adopted_pets', [])
if pet_id not in adopted_pet_list:
adopted_pet_list.append(pet_id)
owner_object['adopted_pets'] = adopted_pet_list
# get and update pet object to show adopted
pet_object = json.loads(pet.get(pet_id))
pet_object['adopted'] = True
pet_object['adopted_by'] = owner_id
# send updates to redis
pet.set(pet_id, json.dumps(pet_object))
user.set(owner_id, json.dumps(owner_object))
return {
'owner': owner_object,
'pet' : pet_object
}
"""
REMINDER ROUTES
"""
def get_keys(key_type):
keys = [Id.decode("utf-8") for Id in user.keys() if '{}:'.format(key_type) in Id.decode("utf-8")]
return keys
def get_reminder_keys():
reminders = [Id.decode("utf-8") for Id in user.keys() if 'reminder:' in Id.decode("utf-8")]
return reminders
@hug.post('/reminder', requires=cors_support)
def add_reminder(body):
reminder_id = get_uuid()
pet_id = body['pet_id']
# create reminder, get ID
body['reminder_id'] = 'reminder:{}'.format(reminder_id)
user.set(body['reminder_id'], json.dumps(body))
# add to pet
pet_object = json.loads(pet.get(pet_id))
pet_object['reminders'] .append(body)
pet.set(pet_id, json.dumps(pet_object))
return pet_object
@hug.get('/reminder', requires=cors_support)
def get_reminder(reminder_id: hug.types.text = None, pet_id: hug.types.text = None):
if reminder_id is None:
if pet_id is None:
# get all reminder_ids
reminder_ids = get_keys(key_type='reminder')
return reminder_ids
else:
# get all reminders for pet_id
pet_object = json.loads(pet.get(pet_id))
return pet_object.get('reminders', [])
else:
# get specific reminder_id object
reminder_object = user.get(reminder_id)
return json.loads(reminder_object)
"""
QUERIES
"""
@hug.get('/breeds', requires=cors_support)
def get_breed_list():
with open('data/breed_list.txt', 'r') as r:
breed_list = json.loads(r.read())
return breed_list
@hug.get('/adopted_pet_numbers', requires=cors_support)
def adopted_pet_numbers():
pets_adopted = []
pet_ids = pet.keys()
for pet_id in pet_ids:
pet_object = json.loads(pet.get(pet_id))
if pet_object['adopted'] == True:
pets_adopted.append(pet_id)
payload = {
'total' : len(pet_ids),
'adopted' : len(pets_adopted)
}
return payload
"""
DOCUMENTS
"""
def get_document_ids():
filenames = [filename for filename in os.listdir('docs') if ('.txt' in filename) and ('1' not in filename) and ('3' not in filename)]
document_ids = [filename.split('.')[1] for filename in filenames]
return document_ids
@hug.get('/document', requires=cors_support)
def get_document(document_id: hug.types.text = None):
if document_id is None:
return get_document_ids()
else:
number = document_id
lookup = {
'0' : 'Adoption Agreement.0.txt',
# '1' : 'Cat Vaccine Schedule.1.txt',
'2' : 'Dog and Cat Safety.2.txt',
# '3' : 'Dog Vaccine Schedule.3.txt',
'4' : 'Microchipping Importance.4.txt',
'5' : 'Proof of Vaccination.5.txt',
'6' : 'Rabies Certificate.6.txt'
}
filename = lookup[document_id]
with open('docs/{}'.format(filename), 'r') as r:
data = json.loads(r.read())
return data
"""
IMAGES
"""
def get_random_image_path_for_breed(breed):
if breed == 'Poodle':
path = 'images/poodle'
filenames = os.listdir(path)
random_file = random.choice(filenames)
return '{}/{}'.format(path, random_file)
elif breed == 'Miniature Schnauzer':
path = 'images/miniature_schnauzer'
filenames = os.listdir(path)
random_file = random.choice(filenames)
return '{}/{}'.format(path, random_file)
elif breed == 'Labrador Retriever':
path = 'images/labrador'
filenames = os.listdir(path)
random_file = random.choice(filenames)
return '{}/{}'.format(path, random_file)
else:
return 'images/quokka.jpg'
@hug.get('/image_for_pet')
def get_image_for_breed(pet_id: hug.types.text):
pet_object = json.loads(pet.get(pet_id))
with open(pet_object['image'], 'rb') as r:
encoded_img = base64.b64encode(r.read())
return encoded_img.decode('utf-8')
"""
CREATE DEMO STUFF
"""
@hug.get('/demo_setup', requires=cors_support)
def demo_setup(response):
# clear owner db
user.flushdb()
# # clear pet db
pet.flushdb()
demo_user = {
'username' : 'jane',
'password' : '1234',
'firstName' : 'Jane',
'lastName' : 'Goodall',
'email' : 'jane@purina.com',
'phoneNumber' : '314-123-4567',
'address' : '1 Purina Drive, St. Louis MO',
'role' : 'user'
}
create_owner(demo_user, response)
demo_owner = {
'username' : 'frank',
'password' : '1234',
'firstName' : 'Frank',
'lastName' : 'Parks',
'email' : 'frank@ilovepets.com',
'address' : '5 Sunny Lane, St. Louis MO',
'phoneNumber' : '314-555-5555'
}
create_owner(demo_owner, response)
# demo_pet1 = {
# 'name' : 'Fluffles',
# 'breed' : 'Poodle',
# 'chipped' : '123-456-789',
# 'age' : '5',
# 'howCheckedIn' : 'Rescued'
# }
# demo_pet2 = {
# 'name' : 'Max',
# 'breed' : 'Labrador Retriever',
# 'chipped' : '999-446-729',
# 'age' : '10',
# 'howCheckedIn' : 'Rescued'
# }
demo_pet3 = {
'name' : 'Irene',
'breed' : 'Miniature Schnauzer',
'chipped' : '631-643-240',
'age' : '3',
'howCheckedIn' : 'Rescued'
}
# create_pet(demo_pet1)
# create_pet(demo_pet2)
create_pet(demo_pet3)
#add encoded_documents to redis
doc_filenames = os.listdir('docs')
doc_filenames = [filename for filename in doc_filenames if '.pdf' in filename]
encoded_doc_list = []
for i, doc_file in enumerate(doc_filenames):
with open('docs/{}'.format(doc_file), "rb") as f:
encodedZip = base64.b64encode(f.read())
title = doc_file.split('.')[0]
decoded = encodedZip.decode('utf-8')
data = {
'title' : title,
'base64' : decoded
}
with open('docs/{}.{}.txt'.format(title, i), 'w') as f:
f.write(json.dumps(data))
#add images webapp paths to redis
file_paths = []
folders = os.listdir('images')
for folder in folders:
try:
filenames = os.listdir('images/{}'.format(folder))
filenames = [filename for filename in filenames if ('DS' not in filename) or ('1' not in filename) or ('3' not in filename)]
for filename in filenames:
file_paths.append('{}/{}'.format(folder, filename))
except:
pass
formatted_image_keys = ['{}:{}'.format(x.split('/')[0], x.split('/')[1][0]) for x in file_paths]
zipped = zip(formatted_image_keys, file_paths)
for image in zipped:
user.set('image:{}'.format(image[0]), image[1])
return {'message' : "Success"}
"""
CLEAR REDIS DATABASE
"""
@hug.post('/clear_redis', requires=cors_support)
def clear_redis():
try:
# clear owner db
user.flushdb()
# clear pet db
pet.flushdb()
return True
except:
return False
if __name__ == '__main__':
user.interface.local()