-
Notifications
You must be signed in to change notification settings - Fork 0
/
#server.py#
executable file
·286 lines (247 loc) · 11.8 KB
/
#server.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
import webapp2
import json
from google.appengine.ext import ndb
import logging
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from collections import namedtuple
from google.appengine.api import search
ACTIONS = namedtuple("ACTIONS", "UPLOAD DOWNLOAD USED_TAGS PATTERN PATTERN_BY_TAG PATTERN_BY_CRITERIA")
URLS = ACTIONS(
UPLOAD="Upload",
DOWNLOAD="Download",
USED_TAGS="UsedTags",
PATTERN="Project",
PATTERN_BY_TAG="ProjectByTag",
PATTERN_BY_CRITERIA="ProjectByCriteria"
)
class Project(ndb.Model):
"Pattern definition model"
name = ndb.StringProperty(required=True)
site = ndb.StringProperty(required=False)
description = ndb.StringProperty(required=True)
garment_family = ndb.StringProperty(required=False)
garment_type = ndb.StringProperty(required=False)
owner = ndb.StringProperty(required=False)
searchable_doc_id = ndb.StringProperty(required=False)
def update(self, newdata):
"Update pattern"
for key, value in newdata.items():
setattr(self, key, value)
class UserPhoto(ndb.Model):
blob_key = ndb.BlobKeyProperty()
pattern_key = ndb.KeyProperty(kind=Project)
class Rest(webapp2.RequestHandler):
def post(self):
#pop off the script name ('/api')
self.request.path_info_pop()
data_dict = json.loads(self.request.body)
tokens = self.request.path_info[1:].split('/')
# Create
if len(tokens) == 1:
searchable_doc = search.Document(
fields=[
search.TextField(name='name', value=data_dict['name']),
search.TextField(name='description', value=data_dict['description'])
])
add_result = search.Index('patterns').put(searchable_doc)
item = Project(
name=data_dict['name'],
description=data_dict['description'],
garment_family=data_dict['garment_family'],
garment_type=data_dict['garment_type'],
owner=data_dict['owner'],
searchable_doc_id=add_result[0].id
)
key = item.put()
self.response.write(json.dumps({'id': key.id()}))
# Update
elif len(tokens) == 2:
item = Project.get_by_id(int(tokens[1]))
item.name = data_dict['name']
item.description = data_dict['description']
item.garment_family = data_dict['garment_family']
item.garment_type = data_dict['garment_type']
item.owner = data_dict['owner']
item.put()
searchable_doc = search.Document(
doc_id=item.searchable_doc_id,
fields=[
search.TextField(name='name', value=data_dict['name']),
search.TextField(name='description', value=data_dict['description'])
])
index = search.Index('patterns')
index.put(searchable_doc)
def get(self):
#pop off the script name ('/api')
self.request.path_info_pop()
#forget about the leading '/' and searate the Data type and the ID
split = self.request.path_info[1:].split('/')
response = []
if len(split) == 1:
# Get Upload URL
if split[0] == URLS.UPLOAD:
url = blobstore.create_upload_url('/upload_photo')
item = {}
item['upload_url'] = url
response.append(item)
# Get Download URL
elif split[0] == URLS.DOWNLOAD:
for file in UserPhoto.query().fetch(20):
logging.info('(1) -----------> {}'.format(file.key))
logging.info('(1) -----------> {}'.format(file.blob_key))
logging.info('(1) -----------> {}'.format(file.key.id()))
blob_info = blobstore.BlobInfo.get(file.blob_key)
logging.info('(1) -----------> Filename: {}'.format(blob_info.filename))
response.append({
'id': file.key.id(),
'blob_key': str(file.blob_key),
'filename': blob_info.filename,
'extension': blob_info.filename.split(".")[-1]
})
elif split[0] == URLS.USED_TAGS:
for pattern in Project.query().order(Project.garment_family).order(Project.garment_type):
# Retrieve a family with this family name
familyToCreateOrAppend = next((f for f in response if f['familyName'] == pattern.garment_family), None)
# If family does not exists
if familyToCreateOrAppend is None:
# Create new family
familyToCreateOrAppend = {
"familyName": pattern.garment_family,
"garments": [{ "fields": {"name": pattern.garment_type }}]
}
response.append(familyToCreateOrAppend)
else:
if not any(t['fields']['name'] == pattern.garment_type for t in familyToCreateOrAppend['garments']):
familyToCreateOrAppend['garments'].append({ "fields": {"name": pattern.garment_type }})
elif split[0] == URLS.PATTERN:
owner = self.request.get('owner')
query = Project.query()
if owner:
query = Project.query(Project.owner == owner)
for pattern in query.fetch(20):
response.append({
"description": pattern.description,
"site": pattern.site,
"id": pattern.key.id(),
"name": pattern.name,
"garment_family": pattern.garment_family,
"garment_type": pattern.garment_type,
"owner": pattern.owner
})
elif split[0] == URLS.PATTERN_BY_TAG:
tag_name = self.request.get('tag')
logging.info('(2) -----------> {} '.format('ProjectByTag'))
query = Project.query(Project.garment_type == tag_name)
for pattern in query.fetch(20):
response.append({
"description": pattern.description,
"site": pattern.site,
"id": pattern.key.id(),
"name": pattern.name,
"garment_family": pattern.garment_family,
"garment_type": pattern.garment_type,
"owner": pattern.owner
})
elif split[0] == URLS.PATTERN_BY_CRITERIA:
criteria = self.request.get('criteria')
logging.info('(2) -----------> {} '.format('ProjectByCriteria'))
query = Project.query(Project.name == criteria)
for pattern in query.fetch(20):
response.append({
"description": pattern.description,
"site": pattern.site,
"id": pattern.key.id(),
"name": pattern.name,
"garment_family": pattern.garment_family,
"garment_type": pattern.garment_type,
"owner": pattern.owner
})
else:
logging.info('(6) -----------')
elif split[0] == URLS.DOWNLOAD:
pattern_key_to_retrieve = split[1]
logging.info('(3) -----------> UPLOAD {} {}'.format(split[0], split[1]))
response = []
pattern = Project.get_by_id(int(pattern_key_to_retrieve))
logging.info('(3) -----------> pattern_key {} '.format(pattern.key))
#files = UserPhoto.query(UserPhoto.pattern_key == pattern_key)
files = UserPhoto.query(UserPhoto.pattern_key == pattern.key).fetch()
for file in files:
#for file in UserPhoto.query().fetch(20):
logging.info('(4) -----------> {}'.format(file.key))
logging.info('(4) -----------> {}'.format(file.blob_key))
logging.info('(4) -----------> {}'.format(file.key.id()))
blob_info = blobstore.BlobInfo.get(file.blob_key)
logging.info('(4) -----------> Filename: {}'.format(blob_info.filename))
response.append({
'id': file.key.id(),
'blob_key': str(file.blob_key),
'filename': blob_info.filename,
'extension': blob_info.filename.split(".")[-1]
})
else:
logging.info('(5) -----------')
#Convert the ID to an int, create a key and retrieve the object
item = globals()[split[0]].get_by_id(int(split[1]))
response = item.to_dict()
response['id'] = item.key.id()
self.response.write(json.dumps(response))
def delete(self):
#pop off the script name ('/api')
self.request.path_info_pop()
#forget about the leading '/' and seperate the Data type and the ID
split = self.request.path_info[1:].split('/')
ndb.Key(split[0], int(split[1])).delete()
class PhotoUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload = self.get_uploads()[0]
logging.info('####################################### UPLOAD self.request.body --> ####################################')
logging.info('[self.request.body]: {}'.format(self.request.body))
logging.info('################################################################################################################')
pattern_id = None
body = self.request.body.split()
iterator = iter(body)
for word in iterator:
if word == 'name="id"':
pattern_id = next(iterator)
logging.info('[body.next()]: {}'.format(pattern_id))
logging.info('################################################################################################################')
pattern = Project.get_by_id(int(pattern_id))
user_photo = UserPhoto(blob_key=upload.key())
user_photo.pattern_key = pattern.key
user_photo.put()
# now look into this: http://stackoverflow.com/questions/11195388/ndb-query-a-model-based-upon-keyproperty-instance
self.response.write(json.dumps({'url':'/view_photo/%s' % upload.key()}))
class ViewPhotoHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, blob_key):
logging.info('(Start)')
""""
<version>0.3.9</version>
<unit>cm</unit>
<author>Timo Virtaneva</author>
<description>This trouser pattern is suitable for women and men for short and long trousers.
There are 2 pleats possible.
No back pockets.
All needed parameters are in variable table.
Check and adjust *** CHECK *** increments
</description>
<notes>The waist band is 2 parts to support adjustable back seam.
Delete the unneeded layouts.
Pockets are adjustable.</notes>
<measurements>trousers.vit</measurements>
"""
blob_reader = blobstore.BlobReader(blob_key)
for line in blob_reader:
if "<description>" in line:
logging.info('>>> {}'.format(line))
logging.info('(End)')
if not blobstore.get(blob_key):
self.error(404)
else:
self.send_blob(blob_key)
app = webapp2.WSGIApplication([
('/api.*', Rest),
('/upload_photo', PhotoUploadHandler),
('/view_photo/([^/]+)?', ViewPhotoHandler),
], debug=True)