Python werkzeug.secure_filename() Examples
The following are 30
code examples of werkzeug.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
, or try the search function
.
Example #1
Source File: kmapi.py From chat with MIT License | 6 votes |
def upload_img(): """Upload img. 上传图片 """ if request.method == 'POST': state = { 'success' : 0, 'message' : "上传图片后缀支持 png, jpg, jpeg, gif 格式", 'url': "" } f = request.files['file'] if allowed_file(f.filename): # 采用绝对路径 filename = 'C:/nlu/data/img/' + secure_filename(f.filename) f.save(filename) state['success'] = 1 state['message'] = "上传图片成功" state['url'] = filename return json.dumps(state)
Example #2
Source File: app.py From Python-DevOps with MIT License | 6 votes |
def wordcount(): f = request.files['file'] f.save( os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)) ) with open(f.filename, 'r') as fopen: hdfs.dump(fopen.read(), '/user/input_wordcount/text') os.system( 'pydoop script -c combiner wordcount.py /user/input_wordcount /user/output_wordcount' ) list_files = hdfs.hdfs().list_directory('/user/output_wordcount') return json.dumps( [ hdfs.load(file['name'], mode = 'rt') for file in list_files if 'SUCCESS' not in file['name'] ] )
Example #3
Source File: app.py From Python-DevOps with MIT License | 6 votes |
def lowercase(): f = request.files['file'] f.save( os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)) ) with open(f.filename, 'r') as fopen: hdfs.dump(fopen.read(), '/user/input_lowercase/text') os.system( "pydoop script --num-reducers 0 -t '' lowercase.py /user/input_lowercase /user/output_lowercase" ) list_files = hdfs.hdfs().list_directory('/user/output_lowercase') return json.dumps( [ hdfs.load(file['name'], mode = 'rt') for file in list_files if 'SUCCESS' not in file['name'] ] )
Example #4
Source File: server.py From crnn-lid with GNU General Public License v3.0 | 6 votes |
def uploadAudio(): def is_allowed(filename): return len(filter(lambda ext: ext in filename, ["wav", "mp3", "ogg"])) > 0 file = request.files.getlist("audio")[0] if file and is_allowed(file.filename): filename = secure_filename(file.filename) file_path = path.join(app.config["UPLOAD_FOLDER"], filename) file.save(file_path) # convert_to_mono_wav(file_path, True) response = jsonify(get_prediction(file_path)) else: response = bad_request("Invalid file") return response
Example #5
Source File: utils.py From flux-ci with MIT License | 6 votes |
def secure_filename(filename): """ Similar to #werkzeug.secure_filename(), but preserves leading dots in the filename. """ while True: filename = filename.lstrip('/').lstrip('\\') if filename.startswith('..') and filename[2:3] in '/\\': filename = filename[3:] elif filename.startswith('.') and filename[1:2] in '/\\': filename = filename[2:] else: break has_dot = filename.startswith('.') filename = werkzeug.secure_filename(filename) if has_dot: filename = '.' + filename return filename
Example #6
Source File: document.py From gransk with Apache License 2.0 | 6 votes |
def secure_path(path): dirname = os.path.dirname(path) filename = os.path.basename(path) file_base, file_ext = os.path.splitext(path) dirname = secure_filename(slugify(dirname, only_ascii=True)) file_base = secure_filename(slugify(file_base, only_ascii=True)) or 'unnamed' file_ext = secure_filename(slugify(file_ext, only_ascii=True)) if file_ext: filename = '.'.join([file_base, file_ext]) else: filename = file_base if len(filename) > 200: filename = '%s__%s' % (filename[:99], filename[-99:]) if dirname: return os.path.join(dirname, filename) return filename
Example #7
Source File: upload_processor.py From sarjitsu with GNU General Public License v3.0 | 6 votes |
def upload_files(target, sessionID, datafiles): """Upload the files to the server directory Keyword arguments: target - The target directory to upload the files to sessionID - The user session ID datafiles - The list of the files to be uploaded Returns: List """ filename_list = [] for datafile in datafiles: filename = secure_filename(datafile.filename).rsplit("/")[0] update_file_metadata(sessionID, filename) filename_list.append(filename) destination = os.path.join(target, filename) app.logger.info("Accepting incoming file: %s" % filename) app.logger.info("Saving it to %s" % destination) datafile.save(destination) return filename_list
Example #8
Source File: app.py From mix-and-match with MIT License | 6 votes |
def classify_upload(): try: # We will save the file to disk for possible data collection. imagefile = flask.request.files['imagefile'] filename_ = str(datetime.datetime.now()).replace(' ', '_') + \ werkzeug.secure_filename(imagefile.filename) filename = os.path.join(UPLOAD_FOLDER, filename_) imagefile.save(filename) logging.info('Saving to %s.', filename) image = exifutil.open_oriented_im(filename) except Exception as err: logging.info('Uploaded image open error: %s', err) return flask.render_template( 'index.html', has_result=True, result=(False, 'Cannot open uploaded image.') ) result = app.clf.classify_image(image) return flask.render_template( 'index.html', has_result=True, result=result, imagesrc=embed_image_html(image) )
Example #9
Source File: mlapi.py From sia-cog with MIT License | 6 votes |
def upload(name): message = "Success" code = 200 try: datasetFolder = "./data/" + name + "/dataset/" projectmgr.ValidateServiceExists(name, constants.ServiceTypes.MachineLearning) if not os.path.exists(datasetFolder): os.makedirs(datasetFolder) if len(request.files) == 0: code = 1002 message = "No file found" return jsonify({"statuscode": code, "message": message}) postedfile = request.files.items(0)[0][1] postedfile.save(os.path.join(datasetFolder, werkzeug.secure_filename(postedfile.filename))) except Exception as e: code = 500 message = str(e) return jsonify({"statuscode": code, "message": message})
Example #10
Source File: server.py From iLID with MIT License | 6 votes |
def uploadAudio(): def is_allowed(filename): return len(filter(lambda ext: ext in filename, ["wav", "mp3", "ogg"])) > 0 file = request.files.getlist("audio")[0] if file and is_allowed(file.filename): filename = secure_filename(file.filename) file_path = path.join(app.config["UPLOAD_FOLDER"], filename) file.save(file_path) # convert_to_mono_wav(file_path, True) response = jsonify(get_prediction(file_path)) else: response = bad_request("Invalid file") return response
Example #11
Source File: app.py From Deep-Exemplar-based-Colorization with MIT License | 6 votes |
def classify_upload(): try: # We will save the file to disk for possible data collection. imagefile = flask.request.files['imagefile'] filename_ = str(datetime.datetime.now()).replace(' ', '_') + \ werkzeug.secure_filename(imagefile.filename) filename = os.path.join(UPLOAD_FOLDER, filename_) imagefile.save(filename) logging.info('Saving to %s.', filename) image = exifutil.open_oriented_im(filename) except Exception as err: logging.info('Uploaded image open error: %s', err) return flask.render_template( 'index.html', has_result=True, result=(False, 'Cannot open uploaded image.') ) result = app.clf.classify_image(image) return flask.render_template( 'index.html', has_result=True, result=result, imagesrc=embed_image_html(image) )
Example #12
Source File: not_hotdog.py From hotdog-not-hotdog with MIT License | 6 votes |
def upload(): # Get the name of the uploaded file file = request.files['file'] # Check if the file is one of the allowed types/extensions if file and allowed_file(file.filename): # remove unsupported chars etc filename = secure_filename(file.filename) #save path save_to=os.path.join(app.config['UPLOAD_FOLDER'], filename) #save file file.save(save_to) #pass file to model and return bool is_hotdog=not_hotdog_model.is_hotdog(save_to) #show if photo is a photo of hotdog return redirect(url_for('classification', result=is_hotdog)) #file show route (not using now)
Example #13
Source File: app.py From tensorflow2.0-coding with MIT License | 6 votes |
def CNN_predict(): global secure_filename file = gConfig['dataset_path'] + "batches.meta" patch_bin_file = open(file, 'rb') label_names_dict = pickle.load(patch_bin_file)["label_names"] img = Image.open(os.path.join(app.root_path, secure_filename)) img = img.convert("RGB") r, g, b = img.split() r_arr = np.array(r) g_arr = np.array(g) b_arr = np.array(b) img = np.concatenate((r_arr, g_arr, b_arr)) image = img.reshape([1, 32, 32, 3])/255 payload = json.dumps({"instances":image.tolist()}) predicted_class=requests.post('http://localhost:9000/v1/models/ImageClassifier:predict',data=payload) predicted_class=np.array(json.loads(predicted_class.text)["predictions"]) prediction=tf.math.argmax(predicted_class[0]).numpy() print(prediction) return flask.render_template(template_name_or_list="prediction_result.html",predicted_class=label_names_dict[prediction])
Example #14
Source File: app.py From tensorflow2.0-coding with MIT License | 6 votes |
def CNN_predict(): global secure_filename img = Image.open(os.path.join(app.root_path, 'predict_img/'+secure_filename)) img = img.convert("RGB") r, g, b = img.split() r_arr = np.array(r) g_arr = np.array(g) b_arr = np.array(b) img = np.concatenate((r_arr, g_arr, b_arr)) image = img.reshape([1, 32, 32, 3])/255 predicted_class = execute.predict(image) print(predicted_class) return flask.render_template(template_name_or_list="prediction_result.html", predicted_class=predicted_class)
Example #15
Source File: image.py From guides-cms with GNU Affero General Public License v3.0 | 6 votes |
def save_image(file_, extension, message, name, email, branch='master'): """ Save image to github as a commit :param file_: Open file object containing image :param: Extension to use for saved filename :param message: Commit message to save image with :param name: Name of user committing image :param email: Email address of user committing image :param branch: Branch to save image to :returns: Public URL to image or None if not successfully saved """ file_name = secure_filename('%s%s%s' % (str(uuid.uuid4()), os.extsep, extension)) path = os.path.join(main_image_path(), file_name) url = None if commit_image_to_github(path, message, file_, name, email, branch=branch) is not None: url = github_url_from_upload_path(path, file_name, branch=branch) return url
Example #16
Source File: views.py From Flask-Framework-Cookbook-Second-Edition with MIT License | 6 votes |
def create_product(): form = ProductForm() if form.validate_on_submit(): name = form.name.data price = form.price.data category = Category.query.get_or_404( form.category.data ) image = form.image.data if allowed_file(image.filename): filename = secure_filename(image.filename) image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) product = Product(name, price, category, filename) db.session.add(product) db.session.commit() flash('The product %s has been created' % name, 'success') return redirect(url_for('catalog.product', id=product.id)) if form.errors: flash(form.errors, 'danger') return render_template('product-create.html', form=form)
Example #17
Source File: views.py From Flask-Framework-Cookbook-Second-Edition with MIT License | 6 votes |
def create_product(): form = ProductForm() if form.validate_on_submit(): name = form.name.data price = form.price.data category = Category.query.get_or_404( form.category.data ) image = form.image.data if allowed_file(image.filename): filename = secure_filename(image.filename) image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) product = Product(name, price, category, filename) db.session.add(product) db.session.commit() flash(_('The product %(name)s has been created', name=name), 'success') return redirect(url_for('catalog.product', id=product.id)) if form.errors: flash(form.errors, 'danger') return render_template('product-create.html', form=form)
Example #18
Source File: kmapi.py From chat with MIT License | 6 votes |
def reset(): """Reset 用用户上传的知识库重置用户所有已有知识库。 """ if request.method == 'POST': state = { 'success' : 0, 'message' : "上传知识库文件后缀应该是.xls" } f = request.files['file'] if allowed_file(f.filename): filename = 'C:/nlu/data/upload/' + secure_filename(f.filename) f.save(filename) # 删除配置(TODO:只能删除其有权限的知识库配置) database.graph.run("MATCH (n:Config) DETACH DELETE n") # 重新导入 database.reset(filename=filename) state['success'] = 1 state['message'] = "重置知识库成功" return json.dumps(state)
Example #19
Source File: kmapi.py From chat with MIT License | 6 votes |
def upload(): """Upload 上传 对已存在的节点覆盖,对不存在的追加。 TODO:只对该用户有权限的知识库有效,无权限的知识库导入无效。 """ if request.method == 'POST': state = { 'success' : 0, 'message' : "上传知识库文件后缀应该是.xls" } f = request.files['file'] if allowed_file(f.filename): # 采用绝对路径 filename = 'C:/nlu/data/upload/' + secure_filename(f.filename) f.save(filename) # 对已存在的节点覆盖,对不存在的追加 database.handle_excel(filename=filename) state['success'] = 1 state['message'] = "上传知识库成功" return json.dumps(state)
Example #20
Source File: main.py From GerbLook with BSD 2-Clause "Simplified" License | 6 votes |
def pcb(uid): uid = secure_filename(uid) basedir = os.path.join(app.config['DATA_DIR'], uid) if not os.path.isdir(basedir): abort(404) project = Project.query.get(uid) detail_file = os.path.join(basedir, 'details.json') try: details = json.load(open(detail_file)) except: details = { 'rendered': True, } images = os.listdir(os.path.join(basedir, 'images')) noalpha = False if 'noalpha' in request.args: noalpha = True return render_template('pcb.html', uid=uid, images=images, noalpha=noalpha, details=details, project=project)
Example #21
Source File: views.py From puzzle with MIT License | 5 votes |
def resources(): """Upload a new resource for an individual.""" ind_id = request.form['ind_id'] upload_dir = os.path.abspath(app.config['UPLOAD_DIR']) req_file = request.files['file'] filename = secure_filename(req_file.filename) file_path = os.path.join(upload_dir, filename) name = request.form['name'] or filename req_file.save(file_path) ind_obj = app.db.individual(ind_id) app.db.add_resource(name, file_path, ind_obj) return redirect(request.referrer)
Example #22
Source File: storage.py From getting-started-python with Apache License 2.0 | 5 votes |
def _safe_filename(filename): """ Generates a safe filename that is unlikely to collide with existing objects in Google Cloud Storage. ``filename.ext`` is transformed into ``filename-YYYY-MM-DD-HHMMSS.ext`` """ filename = secure_filename(filename) date = datetime.datetime.utcnow().strftime("%Y-%m-%d-%H%M%S") basename, extension = filename.rsplit('.', 1) return "{0}-{1}.{2}".format(basename, date, extension)
Example #23
Source File: storage.py From flask-fs with MIT License | 5 votes |
def save(self, file_or_wfs, filename=None, prefix=None, overwrite=None): ''' Saves a `file` or a :class:`~werkzeug.FileStorage` into this storage. If the upload is not allowed, an :exc:`UploadNotAllowed` error will be raised. Otherwise, the file will be saved and its name (including the folder) will be returned. :param file_or_wfs: a file or :class:`werkzeug.FileStorage` file to save. :param string filename: The expected filename in the storage. Optionnal with a :class:`~werkzeug.FileStorage` but allow to override clietn value :param string prefix: a path or a callable returning a path to be prepended to the filename. :param bool overwrite: if specified, override the storage default value. :raise UnauthorizedFileType: If the file type is not allowed ''' if not filename and isinstance(file_or_wfs, FileStorage): filename = lower_extension(secure_filename(file_or_wfs.filename)) if not filename: raise ValueError('filename is required') if not self.file_allowed(file_or_wfs, filename): raise UnauthorizedFileType() if prefix: filename = '/'.join((prefix() if callable(prefix) else prefix, filename)) if self.upload_to: upload_to = self.upload_to() if callable(self.upload_to) else self.upload_to filename = '/'.join((upload_to, filename)) overwrite = self.overwrite if overwrite is None else overwrite if not overwrite and self.exists(filename): raise FileExists(filename) self.backend.save(file_or_wfs, filename) return filename
Example #24
Source File: app.py From tensorflow2.0-coding with MIT License | 5 votes |
def upload_image(): global secure_filename if flask.request.method == "POST": # 设置request的模式为POST img_file = flask.request.files["image_file"] # 获取需要分类的图片 secure_filename = werkzeug.secure_filename(img_file.filename) # 生成一个没有乱码的文件名 img_path = os.path.join(app.root_path, "predict_img/"+secure_filename) # 获取图片的保存路径 img_file.save(img_path) # 将图片保存在应用的根目录下 print("图片上传成功.") """ """ return flask.redirect(flask.url_for(endpoint="predict")) return "图片上传失败"
Example #25
Source File: app.py From Hello-AI with MIT License | 5 votes |
def upload_file(): if request.method == 'POST': import time start_time = time.time() file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(file_path) thisis = app.catordog.run(file_path) os.rename(file_path, os.path.join(app.config['UPLOAD_FOLDER'], thisis + '__' + filename)) print("--- %s seconds ---" % str (time.time() - start_time)) return redirect("/") return redirect(url_for('uploaded_file', filename="facedetect-"+filename)) from os import listdir from os.path import isfile, join htmlpic="" for f in listdir(UPLOAD_FOLDER): if isfile(join(UPLOAD_FOLDER,f)) and f != '.gitignore': print(f) htmlpic += """<span>""" + f.split('__')[0] + """--></span>""" + """ <img width=200px height=150px src='uploads/"""+f+"""'> """ return ''' <!doctype html> <head> <title>Cat Or Dog</title> </head> <h1>Upload new File - Cat or Dog</h1> <form action="" method=post enctype=multipart/form-data> <p><input type=file name=file> <input type=submit value=Upload> </form> '''+htmlpic
Example #26
Source File: app.py From tensorflow2.0-coding with MIT License | 5 votes |
def upload_image(): global secure_filename if flask.request.method == "POST": img_file = flask.request.files["image_file"] secure_filename = werkzeug.secure_filename(img_file.filename) # 生成一个没有乱码的文件名 img_path = os.path.join(app.root_path, "predict_img/"+secure_filename) # 获取图片的保存路径 img_file.save(img_path) print("图片上传成功.") return flask.redirect(flask.url_for(endpoint="predict")) return "图片上传失败"
Example #27
Source File: views.py From edx_data_research with MIT License | 5 votes |
def parse_course_structure(): form = CourseStructureForm() if form.validate_on_submit(): filename = secure_filename(form.course_structure_file.data.filename) with temp_dir_context() as temp_dir: file_path = os.path.join(temp_dir, filename) form.course_structure_file.data.save(file_path) course = form.course.data args = CourseStructure(course, 'localhost', file_path, True) edx_obj = parsing.CourseStructure(args) edx_obj.migrate() return redirect(url_for('parse.parse_course_structure')) return render_template('parse/course_structure.html', form=form)
Example #28
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
Example #29
Source File: main.py From GerbLook with BSD 2-Clause "Simplified" License | 5 votes |
def pcb_state(uid): uid = secure_filename(uid) basedir = os.path.join(app.config['DATA_DIR'], uid) if not os.path.isdir(basedir): abort(404) return jsonify(progress=app.r.get('gerblook/pcb/%s/render-progress' % uid), activity=app.r.get('gerblook/pcb/%s/render-activity' % uid), queue_length=app.r.llen('gerblook/renderqueue'))
Example #30
Source File: main.py From GerbLook with BSD 2-Clause "Simplified" License | 5 votes |
def image(uid, image): uid = secure_filename(uid) image = secure_filename(image) basedir = os.path.join(app.config['DATA_DIR'], uid) if not os.path.isdir(basedir): abort(404) image = os.path.join(basedir, 'images', image) if not os.path.exists(image): abort(404) return send_file(image)