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