本文整理汇总了Python中flask.request.files方法的典型用法代码示例。如果您正苦于以下问题:Python request.files方法的具体用法?Python request.files怎么用?Python request.files使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.request
的用法示例。
在下文中一共展示了request.files方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: infer
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def infer():
f = request.files['img']
# 保存图片
save_father_path = 'images'
img_path = os.path.join(save_father_path, str(uuid.uuid1()) + '.' + secure_filename(f.filename).split('.')[-1])
if not os.path.exists(save_father_path):
os.makedirs(save_father_path)
f.save(img_path)
# 开始预测图片
img = load_image(img_path)
result = exe.run(program=infer_program,
feed={feeded_var_names[0]: img},
fetch_list=target_var)
# 显示图片并输出结果最大的label
lab = np.argsort(result)[0][0][-1]
names = ['苹果', '哈密瓜', '胡萝卜', '樱桃', '黄瓜', '西瓜']
# 打印和返回预测结果
r = '{"label":%d, "name":"%s", "possibility":%f}' % (lab, names[lab], result[0][0][lab])
print(r)
return r
示例2: upload
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def upload():
f = request.files['file']
assert f, "Where's my file?"
filekey = request.form.get('filekey') or str(uuid.uuid1())
assert RE_ALLOWED_FILEKEYS.match('filekey'), 'Unacceptable file key'
permpath = getpath(filekey)
content_range = (f.headers.get('Content-Range') or
request.headers.get('Content-Range'))
if content_range:
result, kwargs = handle_chunked(f, permpath, content_range)
else:
result, kwargs = handle_full(f, permpath)
kwargs['filekey'] = filekey
return jsonify(result=result, **kwargs)
# Flask endpoint
示例3: whitelist_add
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def whitelist_add():
log.info("whitelist_add called")
try:
file_ = request.files["file"]
handle, filename = tempfile.mkstemp()
os.close(handle)
file_.save(filename)
data = request.get_json()
if data and "functions" in data:
functions = data["functions"]
else:
functions = None
bass.whitelist_add(filename, functions)
os.unlink(filename)
except KeyError:
log.exception("")
return make_response(jsonify(message = "Sample file 'file' missing in POST request"), 400)
return jsonify(message = "OK")
示例4: json_classify
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def json_classify():
if request.method == 'POST':
img = Image.open(request.files['file'])
#Format image to Numpy CHW and run inference, get the results of the single output node
results = engine.infer(image_to_np_CHW(img))[0]
#Retrive the results created by the post processor callback
top_class_label, top5 = results[0], results[1]
#Format data for JSON
top5_str = []
for t in top5:
top5_str.append((t[0], str(t[1])))
classification_data = {"top_class": top_class_label, "top5": top5_str}
return jsonify (
data = classification_data
)
else:
return jsonify (
error = "Invalid Request Type"
)
示例5: json_classify
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def json_classify():
if request.method == 'POST':
img = Image.open(request.files['file'])
#Format image to Numpy CHW and run inference, get the results of the single output node
results = engine.infer(image_to_np_CHW(img))[0]
#Retrive the results created by the post processor callback
top_class_label, top5 = results[0], results[1]
#Format data for JSON
top5_str = []
for t in top5:
top5_str.append((t[0], str(t[1])))
classification_data = {"top_class": top_class_label, "top5": top5_str}
return jsonify (
data = classification_data
)
else:
return jsonify (
error = "Invalid Request Type"
)
示例6: predict_image_handler
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def predict_image_handler():
try:
imageData = None
if ('imageData' in request.files):
imageData = request.files['imageData']
else:
imageData = io.BytesIO(request.get_data())
#img = scipy.misc.imread(imageData)
img = Image.open(imageData)
results = predict_image(img)
return json.dumps(results)
except Exception as e:
print('EXCEPTION:', str(e))
return 'Error processing image', 500
# Like the CustomVision.ai Prediction service /url route handles url's
# in the body of hte request of the form:
# { 'Url': '<http url>'}
示例7: listImport
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def listImport(self, force=None, path=None):
_list = request.url_rule.split('/')[2]
file = request.files['file']
force = request.form.get('force')
count = wl.countWhitelist() if _list.lower == 'whitelist' else bl.countBlacklist()
if (count == 0) | (not count) | (force == "f"):
if _list.lower == 'whitelist':
wl.dropWhitelist()
wl.importWhitelist(TextIOWrapper(file.stream))
else:
bl.dropBlacklist()
bl.importBlacklist(TextIOWrapper(file.stream))
status = _list[0]+"l_imported"
else:
status = _list[0]+"l_already_filled"
return render_template('admin.html', status=status, **self.adminInfo())
# /admin/whitelist/export
# /admin/blacklist/export
示例8: send
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def send(current_user=None):
"""
CASSH add
"""
pubkey = request.files['file']
username = request.form['username']
payload = {}
payload.update({'realname': current_user['name'], 'password': current_user['password']})
payload.update({'username': username})
payload.update({'pubkey': pubkey.read().decode('UTF-8')})
try:
req = put(APP.config['CASSH_URL'] + '/client', \
data=payload, \
headers=APP.config['HEADERS'], \
verify=False)
except ConnectionError:
return Response('Connection error : %s' % APP.config['CASSH_URL'])
if 'Error' in req.text:
return Response(req.text)
return redirect('/status')
示例9: predict_image_handler
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def predict_image_handler(project=None, publishedName=None):
try:
imageData = None
if ('imageData' in request.files):
imageData = request.files['imageData']
elif ('imageData' in request.form):
imageData = request.form['imageData']
else:
imageData = io.BytesIO(request.get_data())
img = Image.open(imageData)
results = predict_image(img)
return jsonify(results)
except Exception as e:
print('EXCEPTION:', str(e))
return 'Error processing image', 500
# Like the CustomVision.ai Prediction service /url route handles url's
# in the body of hte request of the form:
# { 'Url': '<http url>'}
示例10: delete
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def delete(self, user_id, file_id):
try:
hard_delete = request.args.get('hard_delete', False)
if not g.file['is_folder']:
if hard_delete == 'true':
os.remove(g.file['uri'])
File.delete(file_id)
else:
File.update(file_id, {'status': False})
else:
if hard_delete == 'true':
folders = Folder.filter(lambda folder: folder['tag'].startswith(g.file['tag']))
for folder in folders:
files = File.filter({'parent_id': folder['id'], 'is_folder': False })
File.delete({'parent_id': folder['id'], 'is_folder': False })
for f in files:
os.remove(f['uri'])
else:
File.update(file_id, {'status': False})
File.update({'parent_id': file_id}, {'status': False})
return "File has been deleted successfully", 204
except:
abort(500, message="There was an error while processing your request --> {}".format(e.message))
示例11: post
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def post(self, **kwargs):
"""
Upload a new report.
"""
# This doesn't exactly follow the JSON API spec, since it doesn't exactly support file uploads:
# https://github.com/json-api/json-api/issues/246
file_name = utils.get_unique_filename()
request.files["report"].save(file_name)
upload_row = models.Upload.create(
status="NOT TREATED",
path=file_name,
message="File has been created, loading in MegaQC is queued.",
user_id=kwargs["user"].user_id,
)
return schemas.UploadSchema(many=False).dump(upload_row), HTTPStatus.CREATED
示例12: upload_pic
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def upload_pic():
""" Default route.
"""
if request.method == 'POST':
image_file = request.files['file']
try:
extension = image_file.filename.rsplit('.', 1)[1].lower()
except IndexError, err:
app.logger.info(err.message)
abort(404)
if image_file and check_extension(extension):
# Salt and hash the file contents
filename = md5(image_file.read() +
str(round(time.time() * 1000))
).hexdigest() + '.' + extension
image_file.seek(0) # Move cursor back to beginning so we can write to disk
image_file.save(os.path.join(app.config['UPLOAD_DIR'], filename))
add_pic(filename)
gen_thumbnail(filename)
return redirect(url_for('show_pic', filename=filename))
else: # Bad file extension
abort(404)
示例13: upload_avatar
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def upload_avatar(dev_key):
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
developer = Developer.query.filter_by(dev_key=dev_key).first()
if developer is not None and developer.avatar is not None:
path = os.path.join(UPLOAD_FOLDER, developer.avatar)
if os.path.exists(path) and os.path.isfile(path):
os.remove(path)
file_type = file.filename.rsplit('.', 1)[1]
filename = generate_file_name(file_type)
file.save(os.path.join(UPLOAD_FOLDER, filename))
developer.avatar = filename
db.session.add(developer)
db.session.commit()
return jsonify(name=filename)
示例14: upload_icon
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def upload_icon(integration_id):
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
integration = Integration.query.filter_by(integration_id=integration_id).first()
if integration is not None and integration.icon is not None:
path = os.path.join(UPLOAD_FOLDER, integration.icon)
if os.path.exists(path) and os.path.isfile(path):
os.remove(path)
file_type = file.filename.rsplit('.', 1)[1]
filename = generate_file_name(file_type)
file.save(os.path.join(UPLOAD_FOLDER, filename))
integration.icon = filename
db.session.add(integration)
db.session.commit()
return jsonify(name=filename)
示例15: upload_file
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import files [as 别名]
def upload_file():
file = request.files['pcap']
if file and allowed_file(file.filename):
hash = hashlib.sha256()
try:
# FIXME: it should be saved before calculate sha256
hash.update(file.read())
except:
print "Unexpected error:", sys.exc_info()
finally:
file.seek(0)
hash_name = "%s" % (hash.hexdigest())
file.save(os.path.join(app.config['UPLOAD_FOLDER'], hash_name))
pcap = {'id' : hash_name, 'date' : datetime.datetime.utcnow()}
pcap_id = db.pcap.insert(pcap)
return redirect(url_for('launch', pcap_id=pcap_id))