-
Notifications
You must be signed in to change notification settings - Fork 0
/
items.py
186 lines (166 loc) · 6.59 KB
/
items.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
from flask import Blueprint, request, jsonify
from google.cloud import datastore
import jwt_functions
client = datastore.Client()
bp = Blueprint('items', __name__, url_prefix='/items')
ITEMS = "items"
ORDERS = "orders"
# function to check for json request and authorization
def check_auth_accept(header):
if (header['Accept'] != 'application/json') and (header['Accept'] != '*/*'):
return jsonify({"Error": "Please make sure the accept is json."}), 406
# if missing/invalid JWT return 401
if 'Authorization' not in header:
return jsonify({"Error": "Missing auth credentials."}), 401
return None
# function to update a item entity
def update_item(entity, content, owner_id):
entity.update({"item_name": content["item_name"], "quantity": content["quantity"],
"item_description": content["item_description"], "owner_id": owner_id})
client.put(entity)
result = client.get(entity.key)
result["id"] = entity.key.id
result["self"] = request.url_root + 'items/' + str(entity.key.id)
return result
@bp.route('', methods=['POST'])
def items_post():
flag = check_auth_accept(request.headers)
if flag:
return flag
payload = jwt_functions.verify_jwt(request)
if not payload:
return jsonify({"Error": "Unauthorized."}), 401
owner_id = payload["sub"]
try:
content = request.get_json()
new_item = datastore.entity.Entity(key=client.key(ITEMS))
result = update_item(new_item, content, owner_id)
return jsonify(result), 201
except KeyError:
return jsonify({"Error": "The request object is missing at least one of the required attributes"}), 400
@bp.route('', methods=['GET'])
def items_get():
flag = check_auth_accept(request.headers)
if flag:
return flag
payload = jwt_functions.verify_jwt(request)
if not payload:
return jsonify({"Error": "Unauthorized."}), 401
query = client.query(kind=ITEMS)
query.add_filter("owner_id", "=", payload["sub"])
item_total = len(list(query.fetch()))
q_limit = int(request.args.get('limit', '5'))
q_offset = int(request.args.get('offset', '0'))
g_iterator = query.fetch(limit=q_limit, offset=q_offset)
pages = g_iterator.pages
results = list(next(pages))
if g_iterator.next_page_token:
next_offset = q_offset + q_limit
next_url = request.base_url + "?limit=" + str(q_limit) + "&offset=" + str(next_offset)
else:
next_url = None
for e in results:
e["id"] = e.key.id
e["self"] = request.url_root + 'items/' + str(e.key.id)
e["total_items"] = item_total
output = {"items": results}
if next_url:
output["next"] = next_url
return jsonify(output), 200
@bp.route('', methods=['PUT', 'DELETE'])
def items_invalid():
# not allowed to put or delete on the entire list of entities
return jsonify({"Error": "These operations are not allowed on the entire list."}), 405
# get a specified item's info
@bp.route('/<id>', methods=['GET'])
def items_get_specific(id):
flag = check_auth_accept(request.headers)
if flag:
return flag
payload = jwt_functions.verify_jwt(request)
if not payload:
return jsonify({"Error": "Unauthorized."}), 401
item_key = client.key(ITEMS, int(id))
item = client.get(key=item_key)
if not item:
return jsonify({"Error": "No item with this item_id exists"}), 404
if item["owner_id"] != payload["sub"]:
return jsonify({"Error": "You are unauthorized to view this."}), 403
item["id"] = item.key.id
item["self"] = request.url_root + 'items/' + str(item.key.id)
return jsonify(item)
@bp.route('/<id>', methods=['PATCH'])
def items_patch_specific(id):
flag = check_auth_accept(request.headers)
if flag:
return flag
payload = jwt_functions.verify_jwt(request)
if not payload:
return jsonify({"Error": "Unauthorized."}), 401
content = request.get_json()
# make sure new requested name is not a duplicate
item_key = client.key(ITEMS, int(id))
item = client.get(key=item_key)
if not item:
return jsonify({"Error": "No item with this item_id exists"}), 404
if item["owner_id"] != payload["sub"]:
return jsonify({"Error": "You are unauthorized to view this."}), 403
for key in content:
if item[key]:
item[key] = content[key]
client.put(item)
item["id"] = item.key.id
item["self"] = request.url_root + 'items/' + str(item.key.id)
return jsonify(item), 200
@bp.route('/<id>', methods=['PUT'])
def items_put_specific(id):
flag = check_auth_accept(request.headers)
if flag:
return flag
payload = jwt_functions.verify_jwt(request)
if not payload:
return jsonify({"Error": "Unauthorized."}), 401
try:
content = request.get_json()
item_key = client.key(ITEMS, int(id))
item = client.get(key=item_key)
if not item:
return jsonify({"Error": "No item with this item_id exists"}), 404
if item["owner_id"] != payload["sub"]:
return jsonify({"Error": "You are unauthorized to view this."}), 403
owner_id = payload["sub"]
result = update_item(item, content, owner_id)
return jsonify(result), 200
except KeyError:
return jsonify({"Error": "The request object is missing at least one of the required attributes"}), 400
@bp.route('/<id>', methods=['DELETE'])
def items_delete_specific(id):
flag = check_auth_accept(request.headers)
if flag:
return flag
payload = jwt_functions.verify_jwt(request)
if not payload:
return jsonify({"Error": "Unauthorized."}), 401
item_key = client.key(ITEMS, int(id))
item = client.get(key=item_key)
if not item:
return jsonify({"Error": "No item with this item_id exists"}), 404
if item["owner_id"] != payload["sub"]:
return jsonify({"Error": "You are unauthorized to view this."}), 403
# check if item is on a order and remove it
if 'orders' in item.keys() and item['orders'] is not None:
order_key = client.key(ORDERS, item['orders']['id'])
order = client.get(key=order_key)
# update order to remove this item
if 'items' in order.keys() and order['items'] is not None:
i = 0
length = len(order['items'])
while i < length:
if item.key.id == order['items'][i]['id']:
order['items'].pop(i)
length = len(order['items'])
client.put(order)
else:
i += 1
client.delete(item_key)
return jsonify(''), 204