本文整理匯總了Python中werkzeug.datastructures.FileStorage方法的典型用法代碼示例。如果您正苦於以下問題:Python datastructures.FileStorage方法的具體用法?Python datastructures.FileStorage怎麽用?Python datastructures.FileStorage使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類werkzeug.datastructures
的用法示例。
在下文中一共展示了datastructures.FileStorage方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_delete_attachments
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def test_delete_attachments(self):
doc = Document.query.get(self.fx.DocumentData.simple.id)
with open("tests/fixtures/smiley.png") as f:
upload = FileStorage(f, 'smiley.png', name='file', content_type='image/png')
attachment = DocumentAttachment.from_upload(upload, None)
attachment.document = doc
db.session.commit()
self.assertEqual('image/png', attachment.image.original.mimetype)
doc = Document.query.get(doc.id)
x = list(doc.attachments)
for att in x:
for y in att.image:
print 1
#print [1 for t in att.image]
pass
self.assertEqual(1, len(doc.attachments))
doc.attachments = []
db.session.commit()
self.assertEqual(0, len(doc.attachments))
示例2: testLocalImageSaveAndRemove
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def testLocalImageSaveAndRemove(self):
public_id = str(uuid.uuid4())
data = self.image_file.read()
stream = io.BytesIO(data)
image = FileStorage(content_type='image/png', filename=u'/etc/init.d/functions.png', name='image_placeholder',
content_length=0, stream=stream)
result = LocalImageStore.save(image, public_id)
self.assertIsNotNone(result)
filename = public_id + ".png"
self.assertEqual(result['url'], "/static/uploaded/" + filename)
self.assertEqual(result['filename'], filename)
file_absolute_path = os.path.join(self.app.config['UPLOAD_FOLDER'], result['filename'])
uploaded_file = open(file_absolute_path, 'rb')
uploaded_data = uploaded_file.read()
self.assertEqual(data, uploaded_data)
uploaded_file.close()
LocalImageStore.remove(file_absolute_path, public_id)
try:
uploaded_file = open(file_absolute_path)
uploaded_file.close()
except IOError as e:
pass
else:
self.fail("The file should be deleted!")
示例3: test_file_service_upload
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def test_file_service_upload(self):
file_name = 'testfile.png'
with open('test/testfile.png', 'rb') as f:
stream = BytesIO(f.read())
file = FileStorage(stream=stream, filename=file_name)
file_name_sanitized = file_service.sanitize_name(file)
file_path = file_service.generate_path(1, 1, testing=True)
file_service.upload_file(file, file_path, file_name_sanitized)
self.assertTrue(os.path.exists("{}/{}".format(file_path, file_name)))
# Delete test upload folder
shutil.rmtree("{}/".format(file_service.UPLOAD_FOLDER_TEST))
示例4: read_data_from_content_type
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def read_data_from_content_type(file: FileStorage, index_column_first: bool = False, separator: str = '',
dtype=None) -> pd.DataFrame:
if not separator:
separator = _get_separator(file.content_type)
return _read_data(file.stream, separator, index_column_first, dtype)
示例5: convert
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def convert(self, value, op):
# Don't cast None
if value is None:
if not self.nullable:
raise ValueError("Must not be null!")
return None
elif isinstance(self.type, Model) and isinstance(value, dict):
return marshal(value, self.type)
# and check if we're expecting a filestorage and haven't overridden `type`
# (required because the below instantiation isn't valid for FileStorage)
elif isinstance(value, FileStorage) and self.type == FileStorage:
return value
try:
return self.type(value, self.name, op)
except TypeError:
try:
if self.type is decimal.Decimal:
return self.type(str(value), self.name)
else:
return self.type(value, self.name)
except TypeError:
return self.type(value)
示例6: size_of_file
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def size_of_file(self, file):
# type: (FileStorage) -> int
return file.content_length
示例7: test_save_file
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def test_save_file(self):
file_path_fixture = self.get_fixture_file_path("thumbnails/th01.png")
th_file = FileStorage(
stream=open(file_path_fixture, "rb"),
filename="th01.png"
)
full_path = thumbnail.save_file(TEST_FOLDER, "instance-id", th_file)
thumbnail.turn_into_thumbnail(full_path, thumbnail.RECTANGLE_SIZE)
im = Image.open(full_path)
(width, height) = im.size
self.assertEqual(width, 150)
self.assertEqual(height, 100)
示例8: process_formdata
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def process_formdata(self, valuelist):
valuelist = (x for x in valuelist if isinstance(x, FileStorage) and x)
data = next(valuelist, None)
if data is not None:
self.data = data
else:
self.raw_data = ()
示例9: has_file
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def has_file(self):
"""Return ``True`` if ``self.data`` is a
:class:`~werkzeug.datastructures.FileStorage` object.
.. deprecated:: 0.14.1
``data`` is no longer set if the input is not a non-empty
``FileStorage``. Check ``form.data is not None`` instead.
"""
warnings.warn(FlaskWTFDeprecationWarning(
'"has_file" is deprecated and will be removed in 1.0. The data is '
'checked during processing instead.'
))
return bool(self.data)
示例10: __call__
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def __call__(self, form, field):
if not (isinstance(field.data, FileStorage) and field.data):
if self.message is None:
message = field.gettext('This field is required.')
else:
message = self.message
raise StopValidation(message)
示例11: add_picture
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def add_picture(self) -> Dict:
"""
Handle an adding of a picture request on server side.
:return: The result json (status of the request, etc.)
"""
result_json = {}
result_json["Called_function"] = EndPoints.ADD_PICTURE
result_json = self.add_std_info(result_json)
# Answer ONLY to PUT HTTP request
if flask.request.method == 'PUT':
try:
# Received : werkzeug.datastructures.FileStorage. Should use ".read()" to get picture's value
f = flask.request.files['image']
# Convert, save and send picture to server
result_json = self.enqueue_and_save_picture(file=f,
result_json=result_json,
queue=QueueNames.FEATURE_TO_ADD)
except Exception as e:
self.logger.error(f"Error during PUT handling {e}")
result_json["Status"] = "Failure"
result_json["Error"] = "Error during Hash computation or database adding"
else:
result_json = self.add_bad_method_info(result_json, good_method_instead="PUT")
return result_json
# Test it with curl 127.0.0.1:5000/add_pict
# ================= ADD PICTURES - WAITING =================
示例12: request_similar_picture
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def request_similar_picture(self) -> Dict:
"""
Handle a request of one picture, to return a list of similar pictures
:return: The result json (status of the request, etc.)
"""
result_json = {}
result_json["Called_function"] = EndPoints.REQUEST_PICTURE
result_json = self.add_std_info(result_json)
# Answer to PUT HTTP request
if flask.request.method == 'POST':
try:
# Received : werkzeug.datastructures.FileStorage. Should use ".read()" to get picture's value
f = flask.request.files['image']
# Convert, save and send picture to server
result_json = self.enqueue_and_save_picture(file=f,
result_json=result_json,
queue=QueueNames.FEATURE_TO_REQUEST)
except Exception as e:
self.logger.error(f"Error during PUT handling {e}")
result_json["Status"] = "Failure"
result_json["Error"] = "Error during Hash computation or database request"
else:
result_json = self.add_bad_method_info(result_json, good_method_instead="POST")
return result_json
# Test it with curl 127.0.0.1:5000/request_similar_picture
示例13: get_results
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def get_results(self) -> Dict:
"""
Handle a retrieval of results
:return: The result json (status of the request, etc.)
"""
result_json = {}
result_json["Called_function"] = EndPoints.GET_REQUEST_RESULT
result_json = self.add_std_info(result_json)
# Answer to PUT HTTP request
if flask.request.method == 'GET':
try:
# Received : werkzeug.datastructures.FileStorage. Should use ".read()" to get picture's value
tmp_id = flask.request.args.get('request_id')
self.logger.debug(f"Request ID to be answered in server : {type(tmp_id)} ==> {tmp_id} ") # {f.read()}
# Fetch results
result_dict = self.database_worker.get_request_result(self.database_worker.cache_db_no_decode, tmp_id)
result_json["Status"] = "Success"
result_json["request_id"] = tmp_id
result_json["results"] = result_dict
except Exception as e:
self.logger.error(f"Error during GET handling {e}")
result_json["Status"] = "Failure"
result_json["Error"] = "Error during Hash computation or database request"
else:
result_json = self.add_bad_method_info(result_json, good_method_instead="GET")
return result_json
# Test it with curl 127.0.0.1:5000/get_results
# ================= REQUEST PICTURES - WAITING =================
示例14: is_request_ready
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def is_request_ready(self) -> Dict:
"""
Handle a check of a request readiness
:return: The result json (status of the request, etc.)
"""
result_json = {}
result_json["Called_function"] = EndPoints.WAIT_FOR_REQUEST
result_json = self.add_std_info(result_json)
# Answer to PUT HTTP request
if flask.request.method == 'GET':
try:
# Received : werkzeug.datastructures.FileStorage. Should use ".read()" to get picture's value
tmp_id = flask.request.args.get('request_id')
self.logger.debug(f"Request ID to be checked if ready in server : {type(tmp_id)} ==> {tmp_id} ") # {f.read()}
# Fetch results
# TODO : Special function for "cleaner/more performant" check ?
_ = self.database_worker.get_request_result(self.database_worker.cache_db_no_decode, tmp_id)
result_json["Status"] = "Success"
result_json["request_id"] = tmp_id
result_json["is_ready"] = True
except Exception as e:
self.logger.error(f"Normal error during GET handling ('is_ready' request) {e}")
result_json["Status"] = "Failure"
result_json["Error"] = "Error during database request"
result_json["is_ready"] = False
else:
result_json = self.add_bad_method_info(result_json, good_method_instead="GET")
return result_json
# Test it with curl 127.0.0.1:5000/is_ready
示例15: enqueue_and_save_picture
# 需要導入模塊: from werkzeug import datastructures [as 別名]
# 或者: from werkzeug.datastructures import FileStorage [as 別名]
def enqueue_and_save_picture(self, file: datastructures.FileStorage, result_json: Dict, queue: QueueNames) -> Dict:
"""
Hash the picture, generate a BMP file, enqueue it, return the result_json with relevant values
:param queue: Queue to add the picture
:param file: the file provided by the client
:param result_json: The result json/dict to which to add standard values
:return: the modified result_json
"""
# Received : werkzeug.datastructures.FileStorage. Should use ".read()" to get picture's value
self.logger.debug(f"Image received in server : {type(file)} ") # {f.read()}
# Compute input picture hash and convert to BMP
f_hash = id_generator.get_SHA1(file)
f_bmp = id_generator.convert_to_bmp(file) # Returns a bytes array
self.logger.debug(f"Image transformed in BMP in server : {type(f_bmp)} ") # {f_bmp}
# Save received picture to disk
picture_import_export.save_picture(f_bmp, get_homedir() / 'datasets' / 'received_pictures' / (str(f_hash) + '.bmp'))
# If the filename need to be used : secure_filename(f.filename)
# Generate uuid from SHA-1 : # Done : Create request UUID ? Or keep image hash ?
tmp_uuid = str(uuid.uuid5(uuid.NAMESPACE_URL, f_hash))
# Enqueue picture to processing
self.logger.debug(f"Adding to feature queue : {f_hash} hash transformed into -> {tmp_uuid} uuid v5") # {f_bmp}
self.database_worker.add_to_queue(self.database_worker.cache_db_decode,
queue_name=queue,
input_id=tmp_uuid,
dict_to_store={"img": f_bmp})
result_json["Status"] = "Success"
result_json["id"] = tmp_uuid
return result_json
# Launcher for this worker. Launch this file to launch a worker