Python werkzeug.utils.secure_filename() Examples
The following are 30
code examples of werkzeug.utils.secure_filename().
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
werkzeug.utils
, or try the search function
.
Example #1
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 #2
Source File: analyses.py From fame with GNU General Public License v3.0 | 6 votes |
def _save_analysis_file(self, id, path): file = request.files['file'] analysis = Analysis(get_or_404(current_user.analyses, _id=id)) dirpath = os.path.join(path, str(analysis['_id'])) filepath = os.path.join(dirpath, secure_filename(file.filename)) # Create parent dirs if they don't exist try: os.makedirs(dirpath) except OSError: pass with open(filepath, "wb") as fd: copyfileobj(file.stream, fd) return filepath
Example #3
Source File: app.py From thrain 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 a empty part without filename if file.filename == '': flash('No selected file') return 'NO FILE SELECTED' if file: filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename)) return post_upload_redirect() return 'Invalid File Format !'
Example #4
Source File: parse.py From scrapydweb with GNU General Public License v3.0 | 6 votes |
def dispatch_request(self, **kwargs): if self.POST: file = request.files.get('file') if not file: flash('No file selected', self.WARN) return redirect(request.url) if file.filename == '': flash('Filename not found', self.WARN) return redirect(request.url) if file.filename.rpartition('.')[-1] not in ALLOWED_EXTENSIONS: flash('Only file type of %s is supported' % ALLOWED_EXTENSIONS, self.WARN) return redirect(request.url) # Non-ASCII would be omitted and may set the filename as 'log' or 'txt' filename = secure_filename(file.filename) if filename in ALLOWED_EXTENSIONS: filename = '%s.%s' % (self.get_now_string(), filename) file.save(os.path.join(self.PARSE_PATH, filename)) return redirect(url_for('.uploaded', node=self.node, filename=filename)) else: url_parse_demo = url_for('.uploaded', node=self.node, filename='ScrapydWeb_demo.log') return render_template(self.template, node=self.node, url_parse_demo=url_parse_demo)
Example #5
Source File: extanalysis.py From ExtAnalysis with GNU General Public License v3.0 | 6 votes |
def upload_file(): if request.method == 'POST': if 'file' not in request.files: return ('error: No File uploaded') file = request.files['file'] if file.filename == '': return ('error: Empty File!') if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) core.updatelog('File Uploaded.. Filename: ' + filename) # saveas = filename.split('.')[0] anls = analysis.analyze(filename) return (anls) else: return ( 'error: Invalid file format! only .crx files allowed. If you\'re trying to upload zip file rename it to crx instead')
Example #6
Source File: controllers.py From sample-platform with ISC License | 6 votes |
def upload(): """Make new upload.""" from run import config form = UploadForm() if form.validate_on_submit(): uploaded_file = request.files[form.file.name] if uploaded_file: filename = secure_filename(uploaded_file.filename) temp_path = os.path.join(config.get('SAMPLE_REPOSITORY', ''), 'TempFiles', filename) uploaded_file.save(temp_path) file_hash = create_hash_for_sample(temp_path) if sample_already_uploaded(file_hash): os.remove(temp_path) form.errors['file'] = ["Sample with same hash already uploaded or queued"] else: g.log.info("New sample added in upload queue") add_sample_to_queue(file_hash, temp_path, g.user.id, g.db) return redirect(url_for('.index')) return { 'form': form, 'accept': form.accept, 'upload_size': (config.get('MAX_CONTENT_LENGTH', 0) / (1024 * 1024)), }
Example #7
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 #8
Source File: google_drive.py From google-authentication-with-python-and-flask with MIT License | 6 votes |
def upload_file(): if 'file' not in flask.request.files: return flask.redirect('/') file = flask.request.files['file'] if (not file): return flask.redirect('/') filename = secure_filename(file.filename) fp = tempfile.TemporaryFile() ch = file.read() fp.write(ch) fp.seek(0) mime_type = flask.request.headers['Content-Type'] save_image(filename, mime_type, fp) return flask.redirect('/')
Example #9
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 #10
Source File: web.py From SSRSpeed with GNU General Public License v3.0 | 6 votes |
def readFileConfig(): if request.method == "POST": if (sc.web_get_status() == "running"): return 'running' ufile = request.files["file"] #data = getPostData() if ufile: if check_file_allowed(ufile.filename): filename = secure_filename(ufile.filename) tmpFilename = os.path.join(app.config["UPLOAD_FOLDER"], filename) ufile.save(tmpFilename) logger.info("Tmp config file saved as {}".format(tmpFilename)) return json.dumps(sc.web_read_config_file(tmpFilename)) else: logger.error("Disallowed file {}".format(ufile.filename)) return FileNotAllowed.errMsg else: logger.error("File upload failed or unknown error.") return WebFileCommonError.errMsg
Example #11
Source File: flask-example.py From python-examples with MIT License | 6 votes |
def upload_csv() -> str: """Upload CSV example.""" submitted_file = request.files["file"] if submitted_file and allowed_filename(submitted_file.filename): filename = secure_filename(submitted_file.filename) directory = os.path.join(app.config["UPLOAD_FOLDER"]) if not os.path.exists(directory): os.mkdir(directory) basedir = os.path.abspath(os.path.dirname(__file__)) submitted_file.save( os.path.join(basedir, app.config["UPLOAD_FOLDER"], filename) ) out = { "status": HTTPStatus.OK, "filename": filename, "message": f"{filename} saved successful.", } return jsonify(out)
Example #12
Source File: server.py From kusanagi with MIT License | 6 votes |
def init_task(task_id): sys.stderr.write("POST REQUEST: init_task/%s" % task_id+"\n") response = "FAILED" if 'tspec_file' not in request.files: response = "tspec_file missing" sys.stderr.write(response + "\n") else: f_tspec = request.files['tspec_file'] if f_tspec.filename == '': response = "tspec_file not selected" sys.stderr.write(response + "\n") elif f_tspec and allowed_file(f_tspec.filename): tspec_filename = secure_filename(f_tspec.filename) task_spec_dict[task_id] = pickle.loads(f_tspec.read()) sys.stderr.write("Received file:\t" + tspec_filename + "\t") response = "DONE" return "init_task/%s: %s" % (task_id, response)
Example #13
Source File: analyses.py From fame with GNU General Public License v3.0 | 6 votes |
def download_support_file(self, id, module, filename): """Download a support file. .. :quickref: Analysis; Download a support file. :param id: id of the analysis. :param module: name of the module. :param filename: name of the file to download. """ analysis = get_or_404(current_user.analyses, _id=id) filepath = os.path.join(fame_config.storage_path, 'support_files', module, str(analysis['_id']), secure_filename(filename)) if os.path.isfile(filepath): return file_download(filepath) else: # This code is here for compatibility # with older analyses filepath = os.path.join(fame_config.storage_path, 'support_files', str(analysis['_id']), secure_filename(filename)) if os.path.isfile(filepath): return file_download(filepath) else: abort(404)
Example #14
Source File: serve.py From at16k with MIT License | 6 votes |
def file_upload(): """ Handle file upload """ try: file = request.files.get('file', None) if file is None: raise Exception('file missing') file_name = secure_filename(file.filename) file_path = os.path.abspath(os.path.join(UPLOAD_DIR, file_name)) file.save(file_path) results = STT_MODEL(file_path) return jsonify(results) except Exception as error: message = str(error) response = jsonify({"message": message}) response.status_code = 500 return response
Example #15
Source File: base.py From AstroBox with GNU Affero General Public License v3.0 | 6 votes |
def copyFileToLocal(self, origin, destination, observerId): try: secureFilename = secure_filename(origin.split('/')[-1:][0]) self.copy( self._cleanFileLocation(origin), self._cleanFileLocation(destination) + '/' + secureFilename, self._progressCb, observerId ) return secureFilename except Exception as e: self._logger.error("copy print file to local folder failed", exc_info = True) return False
Example #16
Source File: __init__.py From AstroBox with GNU Affero General Public License v3.0 | 6 votes |
def getAbsolutePath(self, filename, mustExist=True): """ Returns the absolute path of the given filename in the correct upload folder. Ensures that the file <ul> <li>has any of the extensions listed in SUPPORTED_EXTENSIONS</li> <li>exists and is a file (not a directory) if "mustExist" is set to True</li> </ul> @param filename the name of the file for which to determine the absolute path @param mustExist if set to true, the method also checks if the file exists and is a file @return the absolute path of the file or None if the file is not valid """ filename = self._getBasicFilename(filename) if not util.isAllowedFile(filename.lower(), set(self.SUPPORTED_EXTENSIONS)): return None secure = os.path.join(self._uploadFolder, secure_filename(self._getBasicFilename(filename))) if mustExist and (not os.path.exists(secure) or not os.path.isfile(secure)): return None return secure
Example #17
Source File: attachment.py From mma-dexter with Apache License 2.0 | 6 votes |
def from_upload(cls, upload, user=None, document=None): """ Create a new attachment from an uploaded file, a `werkzeug.FileStorage` object. """ attachment = DocumentAttachment() attachment.document = document attachment.filename = secure_filename(upload.filename) attachment.mimetype = upload.mimetype if user and user.is_authenticated(): attachment.created_by = user # set the data and generate thumbnails attachment.set_data(upload.stream) return attachment
Example #18
Source File: app.py From test_cnn with GNU General Public License v3.0 | 6 votes |
def upload(): if request.method == 'POST': try: # Get the file from post request f = request.files['file'] # Save the file to ./uploads file_path = os.path.join( basepath, 'uploads', secure_filename(f.filename)) f.save(file_path) predict = model.predict(file2xtrain(file_name=file_path)) img_name = vector_to_code(predict[0]) return img_name except Exception as err: return str(err) return None
Example #19
Source File: run_emote.py From emoter 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 current_app.send_static_file('templates/emote-home.html') 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') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(filename) em.analyzeCSV(filename) return redirect(url_for('static', filename="results.csv"))
Example #20
Source File: web.py From aws-greengrass-mini-fulfillment with Apache License 2.0 | 6 votes |
def upload(): log.info('[upload] request') if request.method == 'POST': log.info('[upload] POST request') if 'file' not in request.files: log.error('[upload] Upload attempt with no file') return Response('No file uploaded', status=500) f = request.files['file'] if f.filename == '': log.error('[upload] Upload attempt with no filename') return Response('No filename uploaded', status=500) if f and allowed_file(f.filename): absolute_file = os.path.abspath(UPLOAD_FOLDER + f.filename) log.info('[upload] absolute_filename:{0}'.format(absolute_file)) filename = secure_filename(absolute_file) f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return Response('Uploaded file successfully', status=200) return
Example #21
Source File: summary_app.py From fitlog with Apache License 2.0 | 6 votes |
def save_summary_api(): res = check_uuid_summary(all_data['uuid'], request.json['uuid']) if res != None: return jsonify(res) summary = request.json['summary'] summary_name = request.json['summary_name'] try: summary_name = secure_filename(summary_name) save_summary(all_data['root_log_dir'], summary_name, summary) return jsonify(status='success', summary_name=summary_name) except Exception as e: print(_colored_string("Save summary failed.", 'red')) print(e) import traceback traceback.print_exc() return jsonify(status='fail', msg='Fail to save summary, check server log.')
Example #22
Source File: image_input.py From BentoML with Apache License 2.0 | 6 votes |
def _load_image_data(self, request: Request): if len(request.files): if len(request.files) != 1: raise BadInput( "ImageInput requires one and at least one image file at a time, " "if you just upgraded from bentoml 0.7, you may need to use " "FileInput or LegacyImageInput instead" ) input_file = next(iter(request.files.values())) if not input_file: raise BadInput("BentoML#ImageInput unexpected HTTP request format") file_name = secure_filename(input_file.filename) verify_image_format_or_raise(file_name, self.accept_image_formats) input_stream = input_file.stream else: data = request.get_data() if not data: raise BadInput("BentoML#ImageInput unexpected HTTP request format") else: input_stream = data input_data = self.imread(input_stream, pilmode=self.pilmode) return input_data
Example #23
Source File: __init__.py From Flask-Store with MIT License | 6 votes |
def safe_filename(self, filename): """ If the file already exists the file will be renamed to contain a short url safe UUID. This will avoid overwtites. Arguments --------- filename : str A filename to check if it exists Returns ------- str A safe filenaem to use when writting the file """ while self.exists(filename): dir_name, file_name = os.path.split(filename) file_root, file_ext = os.path.splitext(file_name) uuid = shortuuid.uuid() filename = secure_filename('{0}_{1}{2}'.format( file_root, uuid, file_ext)) return filename
Example #24
Source File: cache.py From renku-python with Apache License 2.0 | 6 votes |
def extract_file(request): """Extract file from Flask request. :raises: `ValidationError` """ files = request.files if 'file' not in files: raise ValidationError('missing key: file') file = files['file'] if file and not file.filename: raise ValidationError('wrong filename: {0}'.format(file.filename)) if file: file.filename = secure_filename(file.filename) return file
Example #25
Source File: main.py From arauto with Apache License 2.0 | 6 votes |
def upload_file(): # check if the post request has the file part if 'file' not in request.files: resp = jsonify({'message' : 'No file part in the request'}) resp.status_code = 400 return resp file = request.files['file'] if file.filename == '': resp = jsonify({'message' : 'No file selected for uploading'}) resp.status_code = 400 return resp if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(os.path.dirname(os.path.abspath(__file__)), app.config['UPLOAD_FOLDER'], filename)) resp = jsonify({'message' : 'File {} successfully uploaded to {}'.format(filename, os.path.dirname(os.path.abspath(__file__)))}) resp.status_code = 201 return resp else: resp = jsonify({'message' : 'Allowed file types are txt, csv, xlsx, xls'}) resp.status_code = 400 return resp
Example #26
Source File: flask_uploads.py From flask-uploads with MIT License | 5 votes |
def get_basename(self, filename): return lowercase_ext(secure_filename(filename))
Example #27
Source File: base.py From AstroBox with GNU Affero General Public License v3.0 | 5 votes |
def localFileExists(self, filename): try: filename = secure_filename(filename) s = open(self._cleanFileLocation(self.getBaseFolder('uploads') + '/' + filename), 'rb') except Exception as e: return False s.close() return True
Example #28
Source File: editor.py From knowledge-repo with Apache License 2.0 | 5 votes |
def file_upload(): """ Uploads images dropped on the web editor's markdown box to static/images and notifies editors by email """ upload_folder = 'images' title = request.form['title'] files = request.files uploadedFiles = [] if files: for img_file in files.values(): filename = secure_filename(title + "_" + img_file.filename).lower() dst_folder = os.path.join(current_app.static_folder, upload_folder) if is_allowed_image_format(img_file): try: img_file.save(os.path.join(dst_folder, filename)) send_from_directory(dst_folder, filename) uploadedFiles += [url_for("static", filename=os.path.join(upload_folder, filename))] except Exception as e: error_msg = "ERROR during image upload: {}".format(str(e)) logger.error(error_msg) return json.dumps({'error_msg': error_msg, 'success': False}) elif is_pdf(filename): from PyPDF2 import PdfFileReader try: src_pdf = PdfFileReader(img_file) filename = os.path.splitext(filename)[0] num_pages = src_pdf.getNumPages() for page_num in range(num_pages): page_png = pdf_page_to_png(src_pdf, page_num) page_name = "{filename}_{page_num}.jpg".format(**locals()) page_png.save(filename=os.path.join(dst_folder, page_name)) uploadedFiles += [url_for("static", filename=os.path.join(upload_folder, page_name))] except Exception as e: error_msg = "ERROR during pdf upload: {}".format(str(e)) logger.error(error_msg) return json.dumps({'error_msg': error_msg, 'success': False}) return json.dumps({'links': uploadedFiles, 'success': True})
Example #29
Source File: application.py From fava with MIT License | 5 votes |
def download_query(result_format): """Download a query result.""" name, data = g.ledger.query_shell.query_to_file( request.args.get("query_string", ""), result_format ) filename = f"{secure_filename(name.strip())}.{result_format}" return send_file(data, as_attachment=True, attachment_filename=filename)
Example #30
Source File: models.py From scout with MIT License | 5 votes |
def attach(self, filename, data): filename = secure_filename(filename) if isinstance(data, unicode_type): data = data.encode('utf-8') hash_obj = hashlib.sha256(data) data_hash = base64.b64encode(hash_obj.digest()) try: with database.atomic(): data_obj = BlobData.create(hash=data_hash, data=data) except IntegrityError: pass mimetype = mimetypes.guess_type(filename)[0] or 'text/plain' try: with database.atomic(): attachment = Attachment.create( document=self, filename=filename, hash=data_hash, mimetype=mimetype) except IntegrityError: attachment = (Attachment .get((Attachment.document == self) & (Attachment.filename == filename))) attachment.hash = data_hash attachment.mimetype = mimetype attachment.save(only=[Attachment.hash, Attachment.mimetype]) return attachment