-
Notifications
You must be signed in to change notification settings - Fork 0
/
userscontroller.py
73 lines (59 loc) · 2.14 KB
/
userscontroller.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
from flask import Flask, request, Response, Blueprint
from encodejson import jsonify
import mongodal
import dailyintakes
mongo = mongodal.MongoDAL()
mongo.connect()
app = Flask(__name__)
collection = "users"
users_controller = Blueprint("users_controller", __name__)
def get_user(username):
user_dict = {"username": username}
cursor = mongo.find(collection, user_dict)
users = [e for e in cursor]
if len(users) == 0:
raise Exception("There is no user {0}".format(username))
elif len(users) == 1:
return users[0]
else:
raise Exception("Why are there more than one {0}".format(username))
@users_controller.route('/user/<username>', methods=['GET'])
def handle_user(username):
try:
return jsonify(get_user(username))
except Exception as err:
return err
@users_controller.route('/user/<username>/status', methods=['GET'])
def get_user_status(username):
try:
user = get_user(username)
return jsonify(dailyintakes.status(user))
except Exception as err:
print 'err: '
print err
print err.args
return jsonify(err)
@users_controller.route('/user/<username>/meals', methods=['GET', 'POST']) # POST params: { recipe_id: ID }
def get_user_meals(username):
try:
user = get_user(username)
user_dict = {"username": username}
if request.method == 'GET':
return jsonify(user['daily_meals'])
if request.method == 'POST':
newmeals = [request.form['recipe_id']]
if 'daily_meals' in user:
newmeals = newmeals + user['daily_meals']
mongo.update_one('users', user_dict, newmeals)
except Exception as err:
return err
@users_controller.route('/user/<username>/meals/<index>', methods=['DELETE'])
def delete_user_meal(username, index):
try:
if request.method == 'DELETE':
user = get_user(username)
user_dict = {"username": username}
newmeals = user['daily_meals'].pop(index)
return jsonify(mongo.update_one(collection, user_dict, {'daily_meals': newmeals}))
except Exception as err:
return err