當前位置: 首頁>>代碼示例>>Python>>正文


Python utils.secure_filename方法代碼示例

本文整理匯總了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 
開發者ID:yeyupiaoling,項目名稱:LearnPaddle2,代碼行數:27,代碼來源:paddle_server.py

示例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') 
開發者ID:AUCR,項目名稱:AUCR,代碼行數:19,代碼來源:routes.py

示例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") 
開發者ID:aakashjhawar,項目名稱:SolveSudoku,代碼行數:19,代碼來源:app.py

示例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) 
開發者ID:jamesacampbell,項目名稱:python-examples,代碼行數:20,代碼來源:flask-example.py

示例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 
開發者ID:certsocietegenerale,項目名稱:fame,代碼行數:18,代碼來源:analyses.py

示例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) 
開發者ID:certsocietegenerale,項目名稱:fame,代碼行數:24,代碼來源:analyses.py

示例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 
開發者ID:paulozip,項目名稱:arauto,代碼行數:23,代碼來源:main.py

示例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 
開發者ID:at16k,項目名稱:at16k,代碼行數:20,代碼來源:serve.py

示例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 
開發者ID:SwissDataScienceCenter,項目名稱:renku-python,代碼行數:18,代碼來源:cache.py

示例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 
開發者ID:thisissoon,項目名稱:Flask-Store,代碼行數:27,代碼來源:__init__.py

示例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.') 
開發者ID:fastnlp,項目名稱:fitlog,代碼行數:18,代碼來源:summary_app.py

示例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 
開發者ID:aws-samples,項目名稱:aws-greengrass-mini-fulfillment,代碼行數:22,代碼來源:web.py

示例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")) 
開發者ID:jddunn,項目名稱:emoter,代碼行數:20,代碼來源:run_emote.py

示例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 
開發者ID:AstroPrint,項目名稱:AstroBox,代碼行數:18,代碼來源:base.py

示例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 
開發者ID:AstroPrint,項目名稱:AstroBox,代碼行數:27,代碼來源:__init__.py


注:本文中的werkzeug.utils.secure_filename方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。