本文整理汇总了Python中werkzeug.utils.secure_filename方法的典型用法代码示例。如果您正苦于以下问题:Python utils.secure_filename方法的具体用法?Python utils.secure_filename怎么用?Python utils.secure_filename使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.utils
的用法示例。
在下文中一共展示了utils.secure_filename方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: infer
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [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_file
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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')
示例3: upload_file
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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")
示例4: upload_csv
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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)
示例5: _save_analysis_file
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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
示例6: download_support_file
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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)
示例7: upload_file
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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
示例8: file_upload
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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
示例9: extract_file
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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
示例10: safe_filename
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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
示例11: save_summary_api
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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.')
示例12: upload
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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
示例13: upload_file
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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"))
示例14: copyFileToLocal
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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
示例15: getAbsolutePath
# 需要导入模块: from werkzeug import utils [as 别名]
# 或者: from werkzeug.utils import secure_filename [as 别名]
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