-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathflask_gae_blobstore.py
330 lines (280 loc) · 9.84 KB
/
flask_gae_blobstore.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
"""
flask_gae_blobstore
~~~~~~~~~~~~~~~~~~~
Flask extension for working with the blobstore & files apis on
App Engine.
:copyright: (c) 2013 by gregorynicholas.
:license: BSD, see LICENSE for more details.
"""
import re
import time
# Uses of a deprecated module 'string'
# pylint: disable-msg=W0402
import string
import random
import logging
from flask import Response, request
from werkzeug import exceptions
from functools import wraps
from google.appengine.api import files
from google.appengine.ext import blobstore
from google.appengine.ext.blobstore import BlobKey, create_rpc
__all__ = [
'delete', 'delete_async', 'fetch_data', 'fetch_data_async', 'BlobKey',
'WRITE_MAX_RETRIES', 'WRITE_SLEEP_SECONDS', 'DEFAULT_NAME_LEN',
'MSG_INVALID_FILE_POSTED', 'UPLOAD_MIN_FILE_SIZE', 'UPLOAD_MAX_FILE_SIZE',
'UPLOAD_ACCEPT_FILE_TYPES', 'ORIGINS', 'OPTIONS', 'HEADERS', 'MIMETYPE',
'RemoteResponse', 'BlobUploadResultSet', 'BlobUploadResult', 'upload_blobs',
'save_blobs', 'write_to_blobstore']
delete = blobstore.delete
delete_async = blobstore.delete_async
fetch_data = blobstore.fetch_data
fetch_data_async = blobstore.fetch_data_async
#:
WRITE_MAX_RETRIES = 3
#:
WRITE_SLEEP_SECONDS = 0.05
#:
DEFAULT_NAME_LEN = 20
#:
MSG_INVALID_FILE_POSTED = 'Invalid file posted.'
#:
UPLOAD_MIN_FILE_SIZE = 1
#:
UPLOAD_MAX_FILE_SIZE = 1024 * 1024
# set by default to images..
#:
UPLOAD_ACCEPT_FILE_TYPES = re.compile('image/(gif|p?jpeg|jpg|(x-)?png|tiff)')
# todo: need a way to easily configure these values..
#:
ORIGINS = '*'
#:
OPTIONS = ['OPTIONS', 'HEAD', 'GET', 'POST', 'PUT']
#:
HEADERS = ['Accept', 'Content-Type', 'Origin', 'X-Requested-With']
#:
MIMETYPE = 'application/json'
class RemoteResponse(Response):
'''Base class for remote service `Response` objects.
:param response:
:param mimetype:
'''
default_mimetype = MIMETYPE
def __init__(self, response=None, mimetype=None, *args, **kw):
if mimetype is None:
mimetype = self.default_mimetype
Response.__init__(self, response=response, mimetype=mimetype, **kw)
self._fixcors()
def _fixcors(self):
self.headers['Access-Control-Allow-Origin'] = ORIGINS
self.headers['Access-Control-Allow-Methods'] = ', '.join(OPTIONS)
self.headers['Access-Control-Allow-Headers'] = ', '.join(HEADERS)
class BlobUploadResultSet(list):
def to_dict(self):
'''
:returns: List of `BlobUploadResult` as `dict`s.
'''
result = []
for field in self:
result.append(field.to_dict())
return result
class BlobUploadResult:
'''
:param successful:
:param error_msg:
:param blob_key:
:param name:
:param type:
:param size:
:param field:
:param value:
'''
def __init__(self, name, type, size, field, value):
self.successful = False
self.error_msg = ''
self.blob_key = None
self.name = name
self.type = type
self.size = size
self.field = field
self.value = value
@property
def blob_info(self):
return blobstore.get(self.blob_key)
def to_dict(self):
'''
:returns: Instance of a dict.
'''
return {
'successful': self.successful,
'error_msg': self.error_msg,
'blob_key': str(self.blob_key),
'name': self.name,
'type': self.type,
'size': self.size,
# these two are commented out so the class is easily json serializable..
# 'field': self.field,
# 'value': self.value,
}
def upload_blobs(validators=None):
'''Method decorator for writing posted files to the `blobstore` using the
App Engine files api. Passes an argument to the method with a list of
`BlobUploadResult` with `BlobKey`, name, type, size for each posted input file.
:param validators: List of callable objects.
'''
def wrapper(fn):
@wraps(fn)
def decorated(*args, **kw):
return fn(uploads=save_blobs(
fields=_upload_fields(), validators=validators), *args, **kw)
return decorated
return wrapper
def save_blobs(fields, validators=None):
'''Returns a list of `BlobUploadResult` with BlobKey, name, type, size for
each posted file.
:param fields: List of `cgi.FieldStorage` objects.
:param validators: List of callable objects.
:returns: Instance of a `BlobUploadResultSet`.
'''
if validators is None:
validators = [
validate_min_size,
# validate_file_type,
# validate_max_size,
]
results = BlobUploadResultSet()
i = 0
for name, field in fields:
value = field.stream.read()
result = BlobUploadResult(
name=re.sub(r'^.*\\', '', field.filename.decode('utf-8')),
type=field.mimetype,
size=len(value),
field=field,
value=value)
if validators:
for fn in validators:
if not fn(result):
result.successful = False
result.error_msg = MSG_INVALID_FILE_POSTED
logging.warn('Error in file upload: %s', result.error_msg)
else:
result.blob_key = write_to_blobstore(
result.value, mime_type=result.type, name=result.name)
if result.blob_key:
result.successful = True
else:
result.successful = False
results.append(result)
else:
result.blob_key = write_to_blobstore(
result.value, mime_type=result.type, name=result.name)
logging.error('result.blob_key: %s', result.blob_key)
if result.blob_key:
result.successful = True
else:
result.successful = False
results.append(result)
i += 1
return results
def _upload_fields():
'''
:returns: List of tuples with the filename & `cgi.FieldStorage` as value.
'''
result = []
for key, value in request.files.iteritems():
if not isinstance(value, unicode):
result.append((key, value))
return result
def get_field_size(field):
'''
:param field: Instance of `cgi.FieldStorage`.
:returns: Integer.
'''
try:
field.seek(0, 2) # Seek to the end of the file
size = field.tell() # Get the position of EOF
field.seek(0) # Reset the file position to the beginning
return size
except:
return 0
def validate_max_size(result, max_file_size=UPLOAD_MAX_FILE_SIZE):
'''Validates an upload input based on maximum size.
:param result: Instance of `BlobUploadResult`.
:param max_file_size: Integer.
:returns: Boolean, True if field validates.
'''
if result.size > max_file_size:
result.error_msg = 'max_file_size'
return False
return True
def validate_min_size(result, min_file_size=UPLOAD_MIN_FILE_SIZE):
'''Validates an upload input based on minimum size.
:param result: Instance of `BlobUploadResult`.
:param min_file_size: Integer.
:returns: Boolean, True if field validates.
'''
if result.size < min_file_size:
result.error_msg = 'min_file_size'
return False
return True
def validate_file_type(result, accept_file_types=UPLOAD_ACCEPT_FILE_TYPES):
'''Validates an upload input based on accepted mime types.
If validation fails, sets an error property to the field arg dict.
:param result: Instance of `BlobUploadResult`.
:param accept_file_types: Instance of a regex.
:returns: Boolean, True if field validates.
'''
# only allow images to be posted to this handler
if not accept_file_types.match(result.type):
result.field.error_msg = 'accept_file_types'
return False
return True
def write_to_blobstore(data, mime_type, name=None):
'''Writes a file to the App Engine blobstore and returns an instance of a
BlobKey if successful.
:param data: Blob data.
:param mime_type: String, mime type of the blob.
:param name: String, name of the blob.
:returns: Instance of a `BlobKey`.
'''
if not name:
name = ''.join(random.choice(string.letters)
for x in range(DEFAULT_NAME_LEN))
blob = files.blobstore.create(
mime_type=mime_type,
_blobinfo_uploaded_filename=name)
with files.open(blob, 'a', exclusive_lock=True) as f:
f.write(data)
files.finalize(blob)
result = files.blobstore.get_blob_key(blob)
# issue with the local development SDK. we can only write to the blobstore
# so fast, so set a retry_count and delay the execution thread between
# each attempt..
for i in range(1, WRITE_MAX_RETRIES):
if result:
break
else:
logging.debug(
'blob still None.. will retry to write to blobstore..')
time.sleep(WRITE_SLEEP_SECONDS)
result = files.blobstore.get_blob_key(blob)
logging.debug('File written to blobstore: key: "%s"', result)
return result
def send_blob_download():
'''Sends a file to a client for downloading.
:param data: Stream data that will be sent as the file contents.
:param filename: String, name of the file.
:param contenttype: String, content-type of the file.
'''
def wrapper(fn):
@wraps(fn)
def decorated(*args, **kw):
data, filename, contenttype = fn(*args, **kw)
headers = {
'Content-Type': contenttype,
'Content-Encoding': contenttype,
'Content-Disposition': 'attachment; filename={}'.format(filename)}
return Response(data, headers=headers)
return decorated
return wrapper