-
Notifications
You must be signed in to change notification settings - Fork 0
/
fabric.py
163 lines (126 loc) · 5.71 KB
/
fabric.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
from flask import *
from google.cloud import datastore
import json
import constants
from json2html import *
from flask import Flask, render_template, request
datastore_client = datastore.Client()
bp = Blueprint('fabric', __name__, url_prefix='/fabrics')
@bp.route('', methods=['POST','GET'])
def fabrics_get_post():
if 'application/json' not in request.accept_mimetypes:
return ({'Error': 'Accept MIME type not supported'}, 406)
# Create a fabric record
if request.method == 'POST':
content = request.get_json()
if "substrate" not in content.keys() or "color" not in content.keys() or "yards" not in content.keys():
return({'Error': 'The request object is missing at least one of the required attributes'}, 400)
# Create new record in db
new_fabric = datastore.entity.Entity(key=datastore_client.key(constants.fabrics))
new_fabric.update({"substrate": content["substrate"], "color": content["color"],
"yards": content["yards"]})
datastore_client.put(new_fabric)
# Add attributes to return
content['id'] = str(new_fabric.key.id)
content['patterns'] = []
content['self'] = request.base_url + '/' + str(new_fabric.key.id)
return (content, 201)
# View all fabric
elif request.method == 'GET':
query = datastore_client.query(kind=constants.fabrics)
q_limit = int(request.args.get('limit', '5'))
q_offset = int(request.args.get('offset', '0'))
l_iterator = query.fetch(limit=q_limit, offset=q_offset)
pages = l_iterator.pages
results = list(next(pages))
if l_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
# Get total number of records
count_query = datastore_client.query(kind=constants.fabrics)
count_results = list(count_query.fetch())
count = len(count_results)
for e in results:
e["self"] = request.base_url + '/' + str(e.key.id)
e["id"] = str(e.key.id)
if 'patterns' not in e or len(e['patterns']) == 0:
e['patterns'] = []
else:
pattern_list = []
for pattern_id in e['patterns']:
pattern_key = datastore_client.key(constants.patterns, int(pattern_id))
pattern = datastore_client.get(key=pattern_key)
pattern_list.append(pattern)
e['patterns'] = pattern_list
output = {"fabrics": results}
if next_url:
output["next"] = next_url
output["total_items"] = count
res = make_response(json.dumps(output))
res.headers.set('Content-Type', 'application/json')
return (res, 200)
else:
return ('', 405)
@bp.route('/<id>', methods=['GET','DELETE', 'PATCH', 'PUT'])
def fabrics_get_delete_update(id):
if 'application/json' not in request.accept_mimetypes:
return ({'Error': 'Accept MIME type not supported'}, 406)
fabric_key = datastore_client.key(constants.fabrics, int(id))
fabric = datastore_client.get(key=fabric_key)
if fabric is None:
return ({'Error': 'No fabric with this fabric_id exists'}, 404)
# Delete a fabric
# Deleting a fabric will remove the fabric id from any associated pattern records
if request.method == 'DELETE':
key = datastore_client.key(constants.fabrics, int(id))
if 'patterns' in fabric.keys() and len(fabric['patterns']) > 0:
for e in fabric['patterns']:
pattern_key = datastore_client.key(constants.patterns, int(e))
pattern = datastore_client.get(key=pattern_key)
pattern['fabric'] = None
datastore_client.put(pattern)
datastore_client.delete(key)
return ('',204)
# View a fabric
elif request.method == 'GET':
if 'patterns' not in fabric.keys():
fabric['patterns'] = []
else:
pattern_list = []
for pattern_id in fabric['patterns']:
pattern_key = datastore_client.key(constants.patterns, int(pattern_id))
pattern = datastore_client.get(key=pattern_key)
pattern_list.append(pattern)
fabric['patterns'] = pattern_list
fabric['id'] = str(fabric.id)
fabric['self'] = request.base_url
res = make_response(json.dumps(fabric))
res.headers.set('Content-Type', 'application/json')
return (res, 200)
# Update a fabric - only updates/overwrites attributes contained in request body
elif request.method == 'PUT' or request.method == 'PATCH':
content = request.get_json()
for attribute in content.keys():
fabric[attribute] = content[attribute]
datastore_client.put(fabric)
if "patterns" not in fabric.keys():
content['patterns'] = []
else:
pattern_list = []
for pattern_id in fabric['patterns']:
pattern_key = datastore_client.key(constants.patterns, int(pattern_id))
pattern = datastore_client.get(key=pattern_key)
pattern_list.append(pattern)
fabric['patterns'] = pattern_list
for attribute in fabric.keys():
content[attribute] = fabric[attribute]
content['id'] = fabric_key.id
self_url = request.base_url
content['self'] = self_url
res = make_response(json.dumps(content))
res.headers.set('Content-Type', 'application/json')
return (res, 200)
else:
return ('', 405)