Python flask.request.files() Examples
The following are 30
code examples of flask.request.files().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
flask.request
, or try the search function
.
Example #1
Source File: upload.py From video2commons with GNU General Public License v3.0 | 16 votes |
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
Example #2
Source File: paddle_server.py From LearnPaddle2 with Apache License 2.0 | 9 votes |
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
Example #3
Source File: server.py From BASS with GNU General Public License v2.0 | 8 votes |
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")
Example #4
Source File: __init__.py From graphene-file-upload with MIT License | 8 votes |
def parse_body(self): """Handle multipart request spec for multipart/form-data""" content_type = request.mimetype if content_type == 'multipart/form-data': operations = load_json_body(request.form.get('operations', '{}')) files_map = load_json_body(request.form.get('map', '{}')) return place_files_in_operations( operations, files_map, request.files ) return super(FileUploadGraphQLView, self).parse_body()
Example #5
Source File: app.py From pluralsight with MIT License | 8 votes |
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>'}
Example #6
Source File: resnet_as_a_service.py From iAI with MIT License | 7 votes |
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" )
Example #7
Source File: ekanalyzer.py From ekanalyzer with GNU Affero General Public License v3.0 | 6 votes |
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))
Example #8
Source File: index.py From watchdog with Apache License 2.0 | 6 votes |
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
Example #9
Source File: resnet_as_a_service.py From iAI with MIT License | 6 votes |
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" )
Example #10
Source File: cassh_web.py From cassh with Apache License 2.0 | 6 votes |
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')
Example #11
Source File: app.py From Custom-vision-service-iot-edge-raspberry-pi with MIT License | 6 votes |
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>'}
Example #12
Source File: app-amd64.py From Custom-vision-service-iot-edge-raspberry-pi with MIT License | 6 votes |
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>'}
Example #13
Source File: flaskgur.py From flaskgur with GNU General Public License v2.0 | 6 votes |
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)
Example #14
Source File: views.py From jbox with MIT License | 6 votes |
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)
Example #15
Source File: views.py From jbox with MIT License | 6 votes |
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)
Example #16
Source File: views.py From MegaQC with GNU General Public License v3.0 | 6 votes |
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
Example #17
Source File: files.py From papers with MIT License | 6 votes |
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))
Example #18
Source File: launch_server.py From fairtest with Apache License 2.0 | 6 votes |
def handler(): """ This is the main handler entry point """ # POST request may require some work if request.method == 'POST': inv = None out = None sens = None upload_file = None expl = None report = None dataset = None # retrieve fields with set values. (allow some empty fields) try: upload_file = request.files['file'] except Exception, error: pass try: dataset = request.form['dataset'] except Exception, error: pass
Example #19
Source File: routes.py From AUCR with GNU General Public License v3.0 | 6 votes |
def get_upload_file_hash(file): """Return uploaded file hash.""" upload_file_dir = current_app.config['FILE_FOLDER'] if current_app.config['OBJECT_STORAGE']: rabbit_mq_server_ip = current_app.config['RABBITMQ_SERVER'] file_hash = str(create_upload_file(file, os.path.join(upload_file_dir))) mq_config_dict = get_mq_yaml_configs() files_config_dict = mq_config_dict["reports"] for item in files_config_dict: if "files" in item: logging.info("Adding " + str(file_hash) + " " + str(item["files"][0]) + " to MQ") index_mq_aucr_report(file_hash, str(rabbit_mq_server_ip), item["files"][0]) p = Process(target=upload_to_object_storage_and_remove, args=(file_hash,)) p.start() else: file_hash = create_upload_file(file, os.path.join(current_app.config['FILE_FOLDER'])) return file_hash
Example #20
Source File: routes.py From AUCR with GNU General Public License v3.0 | 6 votes |
def upload_file(): """Return File Upload flask app analysis blueprint.""" if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also submit a empty part without filename if file.filename == '': flash('No selected file, or that file type is not supported') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file_hash = get_upload_file_hash(file) flash("The " + str(filename) + " md5:" + file_hash + " has been uploaded!") return render_template('upload_file.html', title='Upload File')
Example #21
Source File: app.py From deep-landmark with BSD 3-Clause "New" or "Revised" License | 6 votes |
def index(): if request.method == 'GET': return render_template('index.html') # check url first url = request.form.get('url', None) if url != '': md5 = hashlib.md5(url+app.config['MD5_SALT']).hexdigest() fpath = join(join(app.config['MEDIA_ROOT'], 'upload'), md5+'.jpg') try: response = requests.get(url) with open(fpath, 'wb') as fout: fout.write(response.content) except Exception: abort(403) return redirect(url_for('landmark', hash=md5)) # save file first f = request.files['file'] if f.filename == '': abort(403) md5 = hashlib.md5(f.filename + app.config['MD5_SALT']).hexdigest() fpath = join(join(app.config['MEDIA_ROOT'], 'upload'), md5+'.jpg') f.save(fpath) return redirect(url_for('landmark', hash=md5))
Example #22
Source File: statusapi.py From minemeld-core with Apache License 2.0 | 6 votes |
def import_local_backup(): if 'file' not in request.files: return jsonify(error={'messsage': 'No file in request'}), 400 file = request.files['file'] if file.filename == '': return jsonify(error={'message': 'No file'}), 400 tf = NamedTemporaryFile(prefix='mm-import-backup', delete=False) try: file.save(tf) tf.close() with ZipFile(tf.name, 'r') as zf: contents = zf.namelist() except Exception, e: safe_remove(tf.name) raise e
Example #23
Source File: configdataapi.py From minemeld-core with Apache License 2.0 | 6 votes |
def create(self): tdir = os.path.dirname(os.path.join(self.cpath, self.datafilename)) if not os.path.samefile(self.cpath, tdir): return jsonify(error={'msg': 'Wrong config data filename'}), 400 fdfname = os.path.join(self.cpath, '{}.{}'.format(self.datafilename, self.extension)) if 'file' not in request.files: return jsonify(error={'messsage': 'No file'}), 400 file = request.files['file'] if file.filename == '': return jsonify(error={'message': 'No file'}), 400 tf = NamedTemporaryFile(prefix='mm-extension-upload', delete=False) try: file.save(tf) tf.close() shutil.move(tf.name, fdfname) finally: _safe_remove(tf.name)
Example #24
Source File: resources.py From zou with GNU Affero General Public License v3.0 | 6 votes |
def post(self, instance_id): if not self.is_exist(instance_id): abort(404) self.check_permissions(instance_id) self.prepare_creation(instance_id) tmp_folder = current_app.config["TMP_DIR"] uploaded_file = request.files["file"] thumbnail_path = thumbnail_utils.save_file( tmp_folder, instance_id, uploaded_file ) thumbnail_path = thumbnail_utils.turn_into_thumbnail( thumbnail_path, size=self.size ) file_store.add_picture("thumbnails", instance_id, thumbnail_path) os.remove(thumbnail_path) self.clear_cache_file(instance_id) thumbnail_url_path = thumbnail_utils.url_path( self.data_type, instance_id ) self.emit_event(instance_id) return {"thumbnail_path": thumbnail_url_path}, 201
Example #25
Source File: base.py From zou with GNU Affero General Public License v3.0 | 6 votes |
def post(self): uploaded_file = request.files["file"] file_name = "%s.csv" % uuid.uuid4() file_path = os.path.join(app.config["TMP_DIR"], file_name) uploaded_file.save(file_path) self.is_update = request.args.get("update", "false") == "true" try: result = self.run_import(file_path, ",") return result, 201 except KeyError as e: try: result = self.run_import(file_path, ";") return result, 201 except KeyError as e: current_app.logger.error("A column is missing: %s" % e) return ( {"error": True, "message": "A column is missing: %s" % e}, 400, )
Example #26
Source File: base.py From zou with GNU Affero General Public License v3.0 | 6 votes |
def post(self, project_id): uploaded_file = request.files["file"] file_name = "%s.csv" % uuid.uuid4() file_path = os.path.join(app.config["TMP_DIR"], file_name) uploaded_file.save(file_path) self.is_update = request.args.get("update", "false") == "true" try: result = self.run_import(project_id, file_path, ",") return result, 201 except KeyError as e: try: result = self.run_import(project_id, file_path, ";") return result, 201 except KeyError as e: current_app.logger.error("A column is missing: %s" % e) return ( {"error": True, "message": "A column is missing: %s" % e}, 400, )
Example #27
Source File: app.py From SolveSudoku with MIT License | 6 votes |
def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also submit an empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) filename = str(uuid.uuid4()) + "." + filename.split('.')[1] file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('upload_file', filename=filename)) return render_template("home.html")
Example #28
Source File: premiumizer.py From premiumizer with MIT License | 6 votes |
def get_download_stats(downloader, total_size_downloaded): logger.debug('def get_download_stats started') if downloader.get_status() == 'downloading': size_downloaded = total_size_downloaded + downloader.get_dl_size() progress = round(float(size_downloaded) * 100 / greenlet.task.size, 1) speed = downloader.get_speed(human=False) if speed == 0: eta = ' ' else: tmp = (greenlet.task.size - size_downloaded) / speed eta = ' ' + utils.time_human(tmp, fmt_short=True) greenlet.task.update(speed=utils.sizeof_human(speed) + '/s --- ', dlsize=utils.sizeof_human(size_downloaded) + ' / ' + utils.sizeof_human( greenlet.task.size) + ' --- ', progress=progress, eta=eta) elif downloader.get_status() == 'combining': greenlet.task.update(progress=99, speed=' ', eta=' Combining files') elif downloader.get_status() == 'paused': greenlet.task.update(progress=99, speed=' ', eta=' Download paused') else: logger.debug('Want to update stats, but downloader status is invalid.')
Example #29
Source File: configdataapi.py From minemeld-core with Apache License 2.0 | 5 votes |
def create(self): return jsonify(error=dict(message='Method not allowed on localdb files')), 400
Example #30
Source File: ida_service.py From BASS with GNU General Public License v2.0 | 5 votes |
def bindiff_compare(): logger.info("bindiff_compare called") input_dir = tempfile.mkdtemp() output_dir = tempfile.mkdtemp() try: primary = os.path.join(input_dir, "primary") secondary = os.path.join(input_dir, "secondary") try: request.files["primary"].save(primary) request.files["secondary"].save(secondary) except KeyError: return make_response(jsonify(error="Missing parameter 'primary' or 'secondary'"), 422) timeout = request.form.get('timeout', None) cmd = (BINDIFF_DIFFER, "--primary", primary, "--secondary", secondary, "--output_dir", output_dir) logger.info("Executing %s", " ".join("'%s'" % x for x in cmd)) check_call(cmd, cwd = output_dir, timeout = timeout) db_path = [os.path.join(output_dir, x) for x in os.listdir(output_dir)] if len(db_path) != 1: return make_response(jsonify(error = "BinDiff generated 0 or several output files"), 500) return send_file(open(db_path[0], "rb"), as_attachment = True, attachment_filename = "BinDiff.sqlite3", mimetype = "application/binary") except OSError as err: if err.errno == -9: return make_response(jsonify(error = "Program execution timed out"), 408) else: return make_response(jsonify(error = "Program execution failed with error %d" % err.errno), 500) finally: shutil.rmtree(input_dir) shutil.rmtree(output_dir)