当前位置: 首页>>代码示例>>Python>>正文


Python werkzeug.secure_filename方法代码示例

本文整理汇总了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 
开发者ID:pcbje,项目名称:gransk,代码行数:23,代码来源:document.py

示例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) 
开发者ID:hadleyrich,项目名称:GerbLook,代码行数:25,代码来源:main.py

示例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) 
开发者ID:PacktPublishing,项目名称:Flask-Framework-Cookbook-Second-Edition,代码行数:25,代码来源:views.py

示例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) 
开发者ID:PacktPublishing,项目名称:Flask-Framework-Cookbook-Second-Edition,代码行数:25,代码来源:views.py

示例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)
    ) 
开发者ID:msracver,项目名称:Deep-Exemplar-based-Colorization,代码行数:25,代码来源:app.py

示例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 
开发者ID:twerkmeister,项目名称:iLID,代码行数:21,代码来源:server.py

示例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}) 
开发者ID:tech-quantum,项目名称:sia-cog,代码行数:22,代码来源:mlapi.py

示例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 
开发者ID:NiklasRosenstein,项目名称:flux-ci,代码行数:22,代码来源:utils.py

示例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']
        ]
    ) 
开发者ID:huseinzol05,项目名称:Python-DevOps,代码行数:20,代码来源:app.py

示例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']
        ]
    ) 
开发者ID:huseinzol05,项目名称:Python-DevOps,代码行数:20,代码来源:app.py

示例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 
开发者ID:distributed-system-analysis,项目名称:sarjitsu,代码行数:24,代码来源:upload_processor.py

示例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) 
开发者ID:jaroslaw-weber,项目名称:hotdog-not-hotdog,代码行数:19,代码来源:not_hotdog.py

示例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]) 
开发者ID:zhaoyingjun,项目名称:tensorflow2.0-coding,代码行数:26,代码来源:app.py

示例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) 
开发者ID:zhaoyingjun,项目名称:tensorflow2.0-coding,代码行数:22,代码来源:app.py

示例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 
开发者ID:pluralsight,项目名称:guides-cms,代码行数:25,代码来源:image.py


注:本文中的werkzeug.secure_filename方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。