Python werkzeug 模块,secure_filename() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用werkzeug.secure_filename()

项目:OMW    作者:globalwordnet    | 项目源码 | 文件源码
def uploadFile(current_user):

        format = "%Y-%m-%dT%H:%M:%S"
        now = datetime.datetime.utcnow().strftime(format)

        try:
            file = request.files['file']
        except:
            file = None
        try:
            url = request.form['url']
        except:
            url = None

        if file and allowed_file(file.filename):
            filename = now + '_' +str(current_user) + '_' + file.filename
            filename = secure_filename(filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            file_uploaded = True

        elif url:
            file = urllib.urlopen(url)
            filename = url.split('/')[-1]
            filename = now + '_' +str(current_user) + '_' + filename
            filename = secure_filename(filename)

            if file and allowed_file(filename):

                open(os.path.join(app.config['UPLOAD_FOLDER'], filename),
                     'wb').write(file.read())
            file_uploaded = True

        else:
            filename = None
            file_uploaded = False

        return file_uploaded, filename
项目:gransk    作者:pcbje    | 项目源码 | 文件源码
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
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def _upload_file_to_rackspace(self, file, container, attempt=0):
        """Upload file to rackspace."""
        try:
            chksum = pyrax.utils.get_checksum(file)
            self.cf.upload_file(container,
                                file,
                                obj_name=secure_filename(file.filename),
                                etag=chksum)
            return True
        except Exception as e:
            print "Uploader exception"  # TODO: Log this!
            traceback.print_exc()
            attempt += 1
            if (attempt < 3):
                time.sleep(1)   # Wait one second and try again
                return self._upload_file_to_rackspace(file, container, attempt)
            else:
                print "Tried to upload two times. Failed!"   # TODO: Log this!
                raise
项目:lama    作者:CSE-POST    | 项目源码 | 文件源码
def create(uploaded_files=[], uploaded_url=[]):
    paths = []
    for file in uploaded_files:
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            # TODO check path before save
            path = os.path.join(app.config['UPLOAD_FOLDER'])
            if not os.path.exists(path):
                os.makedirs(path)
            path_filename = os.path.join(path, filename)
            file.save(path_filename)
            paths.append(path_filename)
    inp = Input(paths, urls=uploaded_url)
    analysis_id = inp.analyze()
    logging.info("Analysis {} : {}".format(analysis_id, paths))
    return analysis_id
项目:quokka_ng    作者:rochacbruno    | 项目源码 | 文件源码
def dated_path(obj, file_data):
    try:
        prefix = getattr(obj, 'model_name')
    except BaseException:
        prefix = "undefined"

    parts = op.splitext(file_data.filename)
    rand = random.getrandbits(16)
    filename = u"{name}_{rand}{ext}".format(
        rand=rand, name=parts[0], ext=parts[1]
    )
    filename = secure_filename(filename)
    today = date.today()
    path = u"{prefix}/{t.year}/{t.month}/{filename}".format(
        prefix=prefix, t=today, filename=filename
    )
    return path
项目:guides-cms    作者:pluralsight    | 项目源码 | 文件源码
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
项目:sarjitsu    作者:distributed-system-analysis    | 项目源码 | 文件源码
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
项目:blcf    作者:willard-yuan    | 项目源码 | 文件源码
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):
        # Make the filename safe, remove unsupported chars
        filename = secure_filename(file.filename)
        # Move the file form the temporal folder to
        # the upload folder we setup
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        # Redirect the user to the uploaded_file route, which
        # will basicaly show on the browser the uploaded file
        # CV2
        #img_np = cv2.imdecode(np.fromstring(file.read(), np.uint8), cv2.IMREAD_UNCHANGED) # cv2.IMREAD_COLOR in OpenCV 3.1
        img_np = cv2.imread(os.path.join(app.config['UPLOAD_FOLDER'], filename), -1)
        cv2.imshow("Image", img_np)
        return redirect(url_for('uploaded_file',
                                filename=filename))

# This route is expecting a parameter containing the name
# of a file. Then it will locate that file on the upload
# directory and show it on the browser, so if the user uploads
# an image, that image is going to be show after the upload
项目:zual    作者:ninadmhatre    | 项目源码 | 文件源码
def upload():
    # import pdb
    # pdb.set_trace()
    if request.method == "POST":
        typ = request.form.get('type')
        file = request.files.get('file')
        result = False
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            save_as = os.path.join(app.config['UPLOAD_DIR'], filename)
            try:
                file.save(save_as)
            except Exception as e:
                return render_template('error_code/404.html', msg='Failed to save file...[Err:{0}]'.format(e))
            else:
                result = move_file(typ, save_as, filename, backup=True, linkit=True)

        if not result:
            flash('error:Failed To Upload file..., Try again...')
        else:
            flash('info:File uploaded Successfully!')

    return render_template('upload/upload.html')
项目:pigroom    作者:youjiajia    | 项目源码 | 文件源码
def _rename_temp_file(self, tmp_path, name=None, ext=None):
        name = name if name else self.get_file_md5(tmp_path)
        # ????????
        if os.stat(tmp_path).st_size < 200:
            os.remove(tmp_path)
            raise ValueError('file is too small')

        filename = secure_filename('%s%s' % (name, ext))
        folder = os.path.join(self.root, self.sub_dir, name[:3])
        if not os.path.exists(folder):
            os.makedirs(folder)

        new_path = os.path.join(folder, filename)
        if os.path.exists(new_path):
            os.remove(tmp_path)
        else:
            os.rename(tmp_path, new_path)
        url = os.path.join('/', self.sub_dir, name[:3], filename)
        return url
项目:orchestrate-ai    作者:amrittb    | 项目源码 | 文件源码
def upload_midi():
    file = request.files['file']
    if file and allowed_file(file.filename, set(['mid'])):
        # Make the filename safe, remove unsupported chars
        filename = secure_filename(file.filename)
        # Move the file form the temporal folder to the upload folder
        filepath = os.path.join(app.config['UPLOAD_FOLDER_MIDI'], filename)
        file.save(filepath)

        # Call python script to predict file
        # return labels for each category
        try:
            confidence_score = midi_predictor.predict_song(filepath)
            flash(confidence_score, 'mood')
            return redirect(url_for('index'))
        except Exception, e:
            flash(str(e),'error')
            return redirect(url_for('index'))
    else:
        flash("Invalid File",'error')
        return redirect(url_for('index'))
项目:orchestrate-ai    作者:amrittb    | 项目源码 | 文件源码
def upload_lyrics():
    file = request.files['file']
    print file.filename, "File"
    if file and allowed_file(file.filename, set(['txt'])):
        # Make the filename safe, remove unsupported chars
        filename = secure_filename(file.filename)
        # Move the file form the temporal folder to
        # the upload folder
        file.save(os.path.join(app.config['UPLOAD_FOLDER_LYRICS'], filename))
        # return labels for predicted mood
        lyric_confidence_score = lyrics_predictor.predict_lyrics(file.read())
        flash(lyric_confidence_score, 'mood')    
        return redirect(url_for('index'))
    else:
        flash("Invalid File",'error')
        return redirect(url_for('index'))
项目:Canella-CMS    作者:mush42    | 项目源码 | 文件源码
def store_form(form):
    entry = FormEntry(form_id=g.page.id)
    for f in form:
        field = Field.query.filter_by(form_id=g.page.id).filter_by(name=f.name).one_or_none()
        if field is None:
            continue
        field_entry = FieldEntry(field_id=field.id)
        data = f.data
        if field.type == 'file_input':
            file_data = request.files[field.name]
            filename = '%s-%s-%s.%s' %(field.name, date_stamp(), str(time.time()).replace('.', ''), os.path.splitext(file_data.filename)[-1])
            path = os.path.join(app.config['FORM_UPLOADS_PATH'], secure_filename(filename))
            file_data.save(path)
            data = filename
        field_entry.value = data
        db.session.add(field_entry)
        entry.fields.append(field_entry)
    db.session.add(entry)
    db.session.commit()
项目:webapp    作者:superchilli    | 项目源码 | 文件源码
def upload_avatar():
    form = UploadAvatarForm()
    if form.validate_on_submit():
        avatar = request.files['avatar']
        filename = secure_filename(avatar.filename)
        UPLOAD_FOLDER = current_app.config['UPLOAD_FOLDER']
        ALLOWED_EXTENTIONS = set(['jpg', 'png', 'jpeg', 'gif'])
        flag = '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENTIONS
        if not flag:
            flash('Error file types.')
            return redirect(url_for('.user', username=current_user.username))
        avatar.save(os.path.join(UPLOAD_FOLDER, filename))
        current_user.user_avatar = os.path.join(UPLOAD_FOLDER, filename)

        db.session.add(current_user)
        flash('Your avatar has been updated.')
        return redirect(url_for('.user', username=current_user.username))
    return render_template('upload_avatar.html', form=form)
项目:webdataconnector_ml    作者:DoubleEE    | 项目源码 | 文件源码
def upload_file_kmeans():

    file1 = request.files['trainfile']
    if file1 and allowed_file(file1.filename):
        trainingfilename = secure_filename(file1.filename)
        file1.save(os.path.join(app.config['UPLOAD_FOLDER'], trainingfilename))

    trainingfilename = 'uploads/' + trainingfilename
    my_cluster_df = parse_file(trainingfilename)

    my_cluster_colnames = list(my_cluster_df.columns.values)
    my_cluster_colnames.extend(['cluster'])
    my_cluster_datatypes = []

    list_dataypes = list(my_cluster_df.dtypes)
    for col in list_dataypes:
        if col == 'object':
            my_cluster_datatypes.append('string')
        else:
            my_cluster_datatypes.append('float')
    my_cluster_datatypes.extend(['float'])

    return (json.dumps([my_cluster_colnames, my_cluster_datatypes]))
项目:vilfredo-core    作者:fairdemocracy    | 项目源码 | 文件源码
def create_image_filename(image_filename, filename_append_list=[]):
    '''
    .. function:: create_image_filename(image_filename, filename_append_list=[])

    Generate a filename with optional strings appended.

    :param image_filename: file owner
    :type image_filename: User
    :param image_filename: list of strings to append to the gnerated filename
    :type image_filename: List
    :rtype: String
    '''
    from werkzeug import secure_filename
    new_filename = secure_filename(image_filename)
    fix_filename = os.path.splitext(new_filename)

    # Optionally append strings, question id etc
    for append in filename_append_list:
        new_filename += '_' + append

    app.logger.debug("new_filename + appendics = %s", new_filename)
    new_filename = hash_string(new_filename) + fix_filename[1]
    return new_filename
项目:sia-cog    作者:deepakkumar1984    | 项目源码 | 文件源码
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})
项目:LTHCourseStatistics    作者:TabTabTab    | 项目源码 | 文件源码
def course_summary():
    if request.method == 'POST' and 'course_results' in request.files:
        pdf_file = request.files['course_results']
        if pdf_file and allowed_file(pdf_file.filename):
            original_filename = secure_filename(pdf_file.filename)
            unique_filename = create_unique_filename(app.config['UPLOAD_FOLDER'],
                                                     original_filename)
            pdf_file.save(os.path.join(app.config['UPLOAD_FOLDER'], unique_filename))
            pdf_abs_path = os.path.abspath(os.path.join(app.config['UPLOAD_FOLDER'],
                                                        unique_filename))
            student_course_summary = None
            try:
                student_course_summary = course_statistics.get_course_statistics(
                    pdf_abs_path)
            except course_statistics.ReadPDFException as e:
                return render_template('failure.html',
                                       title='Failure',
                                       redirect=True,
                                       message='It seems the file you provided cound not be read as a PDF.')

            return render_template('student_summary_%s.html' % student_course_summary.language,
                                   title='Summary',
                                   student_summary=student_course_summary)

    return redirect(url_for('index'))
项目:MyDocker    作者:xautlmx    | 项目源码 | 文件源码
def bcresrv():
    form = Upload()
    if form.validate_on_submit():
        session['filename'] = secure_filename(form.file.data.filename)
        if session.get('filename'):
            if session.get('filename').split('.')[-1] in ALLOWED_EXTENSIONS:
                form.file.data.save('uploads/' + session.get('filename'))
                cmd = "mydocker  --bcreatesrv  ./uploads/%s > /dev/null &" %session.get('filename')
                os.system(cmd)
                flash('The Server Containers is being created!')
                return redirect(url_for('index'))
            else:
                flash('Looks like you do not choose a excel file!')
                return redirect(url_for('bcresrv'))
        else:
            flash('Looks like you do not choose any file!')
            return redirect(url_for('bcresrv'))
    return render_template('bcresrv.html',form=form)

#??????????????
项目:MyDocker    作者:xautlmx    | 项目源码 | 文件源码
def bcrecli():
    form = Upload()
    if form.validate_on_submit():
        session['filename'] = secure_filename(form.file.data.filename)
        if session.get('filename'):
            if session.get('filename').split('.')[-1] in ALLOWED_EXTENSIONS:
                form.file.data.save('uploads/' + session.get('filename'))
                cmd = "mydocker  --bcreatecli  ./uploads/%s > /dev/null &" %session.get('filename')
                os.system(cmd)
                flash('The Client Containers is being created!')
                return redirect(url_for('index'))
            else:
                flash('Looks like you do not choose a excel file!')
                return redirect(url_for('bcrecli'))
        else:
            flash('Looks like you do not choose any file!')
            return redirect(url_for('bcrecli'))
    return render_template('bcrecli.html',form=form)

#??????????????
项目:MyDocker    作者:xautlmx    | 项目源码 | 文件源码
def bdelsrv():
    form = Upload()
    if form.validate_on_submit():
        session['filename'] = secure_filename(form.file.data.filename)
        if session.get('filename'):
            if session.get('filename').split('.')[-1] in ALLOWED_EXTENSIONS:
                form.file.data.save('uploads/' + session.get('filename'))
                cmd = "mydocker  --bdelsrv  ./uploads/%s > /dev/null &" %session.get('filename')
                os.system(cmd)
                flash('The Server Containers is being deleted!')
                return redirect(url_for('index'))
            else:
                flash('Looks like you do not choose a excel file!')
                return redirect(url_for('bdelsrv'))
        else:
            flash('Looks like you do not choose any file!')
            return redirect(url_for('bdelsrv'))
    return render_template('bdelsrv.html',form=form)

#??????????????
项目:MyDocker    作者:xautlmx    | 项目源码 | 文件源码
def bdelcli():
    form = Upload()
    if form.validate_on_submit():
        session['filename'] = secure_filename(form.file.data.filename)
        if session.get('filename'):
            if session.get('filename').split('.')[-1] in ALLOWED_EXTENSIONS:
                form.file.data.save('uploads/' + session.get('filename'))
                cmd = "mydocker  --bdelcli  ./uploads/%s > /dev/null &" %session.get('filename')
                os.system(cmd)
                flash('The Client Containers is being deleted!')
                return redirect(url_for('index'))
            else:
                flash('Looks like you do not choose a excel file!')
                return redirect(url_for('bdelcli'))
        else:
            flash('Looks like you do not choose any file!')
            return redirect(url_for('bdelcli'))
    return render_template('bdelcli.html',form=form)

#????????????
项目:toll_road    作者:idosekely    | 项目源码 | 文件源码
def data(command):
    def handle_file():
        f_name = request.args.get('file_name')
        path = app.config['UPLOAD_FOLDER']
        if not f_name:
            path, f_name = os.path.split(app._cr.csv_file)
        return path, f_name

    def _set_data_file(path, f_name):
        _file = os.path.join(path, f_name)
        app._cr.csv_file = _file
        app._ar.csv_file = _file

    def allowed_file(filename):
        return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

    if request.method == 'GET':
        if command == 'set':
            path, f_name = handle_file()
            _set_data_file(path, f_name)
            return 'data file set to %s\n' % f_name
        elif command == 'download':
            path, f_name = handle_file()
            return send_from_directory(path, f_name, as_attachment=True)
        elif command == 'upload':
            return render_template('upload_file.html')
        elif command == 'list':
            files = os.listdir(app.config['UPLOAD_FOLDER'])
            files = [f for f in files if allowed_file(f)]
            return render_template('file_list.html', file_list=files)

    if request.method == 'POST':
        file = request.files['data_file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return "File Saved!\n"
项目:luminance    作者:nginth    | 项目源码 | 文件源码
def event_upload(request, event, form):
    if not form.validate():
        print('upload failed')
        flash('Upload failed.')
        return redirect(url_for('events.event_detail', event_id=event.id))
    if current_user.is_anonymous:
        print('user not logged in')
        flash('You must be logged in to do this.')
        return redirect(url_for('events.event_detail', event_id=event.id))
    if current_user not in event.users:
        flash('You must be registered for this event to do this.')
        return redirect(url_for('events.event_detail', event_id=event.id))

    photo = form.photo.data
    filename = secure_filename(form.photo.data.filename)
    filename = current_user.username + '_' + filename
    try:
        abs_filename = getcwd() + '/luminance/static/photos/' + filename
        form.photo.data.save(abs_filename)
        p = Photo(url='/static/photos/' + filename)
        current_user.photos.append(p)
        current_user.exp += 1
        event.photos.append(p)
        db_session.add(p)
        db_session.add(current_user)
        db_session.add(event)
        db_session.commit()
    except Exception:
        print_exc()
        flash('Upload failed.')
        return redirect(url_for('events.event_list'))

    flash('Upload successful!')
    return redirect(url_for('events.event_list'))
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def _upload_file(self, file, container):
        """Upload a file into a container/folder."""
        try:
            print "coming here"
            filename = secure_filename(file.filename)
            if not os.path.isdir(os.path.join(self.upload_folder, container)):
                os.makedirs(os.path.join(self.upload_folder, container))
                print "not saved"
            file.save(os.path.join(self.upload_folder, container, filename))
            print "saved"
            return True
        except Exception:
            return False
项目:odoo-product-configurator    作者:pledra    | 项目源码 | 文件源码
def parse_upload_file(self, field_name, multi=False):
        """ Parse uploaded file from request.files """
        # TODO: Set allowed extensions in the backend and compare
        files = request.httprequest.files.getlist(field_name)
        attachments = []
        for file in files:
            attachments.append({
                'name': secure_filename(file.filename),
                'datas': base64.b64encode(file.stream.read())
            })
            if not multi:
                return attachments
        return attachments
项目:polichombr    作者:ANSSI-FR    | 项目源码 | 文件源码
def ui_sample_upload():
    """
    Sample creation from binary file.
    """
    upload_form = UploadSampleForm()
    families_choices = [(0, "None")]
    families_choices += [(f.id, f.name) for f in Family.query.order_by('name')]
    upload_form.family.choices = families_choices

    if upload_form.validate_on_submit():
        family_id = upload_form.family.data
        zipflag = upload_form.zipflag.data
        family = None
        if family_id != 0:
            family = api.get_elem_by_type("family", family_id)

        for mfile in upload_form.files.raw_data:
            file_data = mfile.stream
            file_name = secure_filename(mfile.filename)

            samples = api.dispatch_sample_creation(
                file_data,
                file_name,
                g.user,
                upload_form.level.data,
                family,
                zipflag)
            if len(samples) == 0:
                flash("Error during sample creation", "error")
            else:
                for sample in samples:
                    flash("Created sample " + str(sample.id), "success")
    return redirect(url_for('index'))
项目:bayes-whales    作者:kern    | 项目源码 | 文件源码
def classify_url():
    if 'url' in flask.request.args:
        imageurl = flask.request.args.get('url', '')
        try:
            string_buffer = StringIO.StringIO(
                urllib.urlopen(imageurl).read())
            image = caffe.io.load_image(string_buffer)

        except Exception as err:
            # For any exception we encounter in reading the image, we will just
            # not continue.
            logging.info('URL Image open error: %s', err)
            return json.dumps({ 'accuracy': [], 'specificity': [] })

        logging.info('Image: %s', imageurl)
        result = app.clf.classify_image(image)
        accuracy = [{ 'label': label, 'score': score } for label, score in result[2]]
        return json.dumps({ 'image': embed_image_html(image), 'accuracy': accuracy, 'specificity': accuracy })
    else:
        try:
            # We will save the file to disk for possible data collection.
            imagefile = flask.request.files['file']
            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 json.dumps({ 'accuracy': [], 'specificity': [] })

        result = app.clf.classify_image(image)
        accuracy = [{ 'label': label, 'score': score } for label, score in result[2]]
        return json.dumps({ 'image': embed_image_html(image), 'accuracy': accuracy, 'specificity': accuracy })
项目:logo-detect    作者:sunbinbin1991    | 项目源码 | 文件源码
def upload():
    # remove exsiting files
    exsiting_files = os.listdir(app.config['UPLOAD_FOLDER'])
    for file in exsiting_files:
        os.remove(os.path.join(app.config['UPLOAD_FOLDER'], file))

    # Get the name of the uploaded files
    uploaded_files = request.files.getlist("file[]")
    filenames = []
    for file in uploaded_files:
        # Check if the file is one of the allowed types/extensions
        if file and allowed_file(file.filename):
            # Make the filename safe, remove unsupported chars
            filename = secure_filename(file.filename)
            # Move the file form the temporal folder to the upload
            # folder we setup
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            # Save the filename into a list, we'll use it later
            filenames.append(filename)
            # Redirect the user to the uploaded_file route, which
            # will basicaly show on the browser the uploaded file

    # Load an html page with a link to each uploaded file
    results = identify_logos(app.config['UPLOAD_FOLDER'])
    return render_template('upload.html', results=results, length=len(results))

# This route is expecting a parameter containing the name
# of a file. Then it will locate that file on the upload
# directory and show it on the browser, so if the user uploads
# an image, that image is going to be show after the upload
项目:flask_boilerplate    作者:sakib    | 项目源码 | 文件源码
def upload_file_handler(file):
    # Save unique file per user
    filename = str(current_user.id) + "_" + secure_filename(file.filename)
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    current_user.file = filename
    # Delete old file
    path = os.path.abspath(app.config['UPLOAD_FOLDER'])
    list = os.listdir(path)
    for item in list:
        id = int(item.split('_')[0])
        if id == int(current_user.id) and filename != item:
            os.remove(os.path.join(path, item))
项目:bedrock-core    作者:Bedrock-py    | 项目源码 | 文件源码
def write_source_file(dataloader_path, src_id, uploadedfile):
    """Writes the a dataloader source into a file from web request file upload."""
    rootpath = os.path.join(dataloader_path, src_id, 'source/')
    filename = werkzeug.secure_filename(uploadedfile.filename)
    if not os.path.exists(rootpath):
        os.makedirs(rootpath, DIRMASK)
    filepath = os.path.join(rootpath, filename)
    uploadedfile.save(filepath)
    return rootpath, filepath
项目:ImgPy    作者:vladlenomg    | 项目源码 | 文件源码
def upload_img():
    #http://flask.pocoo.org/docs/0.10/patterns/fileuploads/
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            try:
                filename = secure_filename(file.filename)
                if len(filename) > 30:
                    filename = filename[0:30]+'~.'+filename.split('.')[-1]
                new_id = get_last_id() + 1
                new_filename = filename
                new_url = short_url.encode_url(new_id)
                img_path = new_url+'.'+filename.split('.')[-1]
                file.save(os.path.join(UPLOAD_FOLDER, img_path))
                g.db.execute("INSERT INTO pics (id, filename, url, imgpath) VALUES (?, ?, ?, ?)", (new_id, new_filename, new_url, img_path))
                g.db.commit()
                save_thumbnail(img_path)
                #return redirect(url_for('upload_img', filename=filename))
                return redirect('/show/'+new_url)
            except Exception as e:
                return str(e)
        else:
            return "Wrong file!"
    else:
        recent = recentlyUploaded()
        return render_template('index.html', STATIC_DIR = STATIC_DIR, TEMPLATES_DIR=TEMPLATES_DIR, recent = recent,)
项目:podofo    作者:VieVie31    | 项目源码 | 文件源码
def search_page():
    query = request.args.get('s')
    page  = request.args.get('p')

    if not query:
        return render_template('search.html', allow_upload=app.config['ALLOW_UPLOAD'], count_pdf=count_pdf())

    try:
        page = abs(int(page))
    except:
        page = 0

    query = query.lower()
    query = unicodedata.normalize('NFKD', query).encode('ASCII', 'ignore')
    words = query.split()[:5] #max 5 words for querying...
    words = map(secure_filename, words)
    query = " ".join(words)

    words = map(lemmatize, words)

    if not words:
        return render_template('search.html')

    rows, speed, next_button = get_results(words, page)

    if next_button:
        next_button = page + 1

    return render_template('results.html', user_request=query, rows=rows, speed=speed, next_button=next_button)
项目:podofo    作者:VieVie31    | 项目源码 | 文件源码
def return_pdf(pdf_name):
    try:
        return redirect(url_for('static', filename=app.config['PDF_DIR'] + secure_filename(pdf_name)))
    except:
        abort(404)
项目:mybookshelf2    作者:izderadicka    | 项目源码 | 文件源码
def upload():
    file = request.files['file']
    if file:
        filename = secure_filename(file.filename)
        temp_dir = tempfile.mkdtemp(dir=current_app.config['UPLOAD_DIR'])
        tdir = os.path.split(temp_dir)[1]
        full_name = os.path.join(temp_dir, filename)
        file.save(full_name)
        result = logic.check_uploaded_file(file.mimetype, full_name)
        if result:
            os.remove(full_name)
            return jsonify(**result)
        return jsonify(result='ok', file=os.path.join(tdir, filename))
    return jsonify(error='no file')
项目:isard    作者:isard-vdi    | 项目源码 | 文件源码
def upload_backup(self,handler):
        path='./backups/'
        id=handler.filename.split('.tar.gz')[0]
        filename = secure_filename(handler.filename)
        handler.save(os.path.join(path+filename))
        import tarfile,pickle
        #~ with app.app_context():
            #~ dict=r.table('backups').get(id).run(db.conn)
            #~ r.table('backups').get(id).update({'status':'Uncompressing backup'}).run(db.conn)
        #~ path=dict['path']

        with tarfile.open(path+handler.filename, "r:gz") as tar:
            tar.extractall(path)
            tar.close()
        #~ with app.app_context():
            #~ r.table('backups').get(id).update({'status':'Loading data..'}).run(db.conn)
        with open(path+id+'.rethink', 'rb') as isard_rethink_file:
            isard_rethink = pickle.load(isard_rethink_file)
        with app.app_context():
            log.info(r.table('backups').insert(isard_rethink, conflict='update').run(db.conn))
        with app.app_context():
            r.table('backups').get(id).update({'status':'Finished uploading'}).run(db.conn)
        try:
            os.remove(path+id+'.json')
            os.remove(path+id+'.rethink')
        except OSError as e:
            log.error(e)
            pass
项目:gSewa    作者:RazinDangol    | 项目源码 | 文件源码
def process():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filedir = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(filedir)
            task = populate.apply_async(args=[filedir])
            return jsonify({'location': url_for('taskstatus', task_id=task.id)})
        else:
            flash('Please upload datasheet of excel format')
            return redirect(url_for('index'))
项目:Narralyzer    作者:WillemJan    | 项目源码 | 文件源码
def analyze():
    # Combine all characters from all chapters into one long list

    import collections

    val = collections.OrderedDict()

    for item in sorted(request.args):
        if item.startswith('ner_'):
            if not int(item.replace('ner_', '').split('_')[0]) in val:
                val[int(item.replace('ner_', '').split('_')[0])] = collections.OrderedDict()
            val[int(item.replace('ner_', '').split('_')[0])][int(item.replace('ner_', '').split('_')[1])] = request.args.get(item)

    all_characters = []
    name = secure_filename(request.args.get('filename').split('.')[0])
    input_characters = ast.literal_eval(urllib.unquote(request.args.get('characters').decode('utf8')))
    aura = ast.literal_eval(urllib.unquote(request.args.get('aura').decode('utf8')))
    counter = 1

    for char in val:
        characters = []
        for i in val[char]:
            if val[char][i].strip():
                all_characters.append(val[char][i])
                characters.append(val[char][i])
        visualize_ners.render_chapter(0, name + "_" + str(counter), characters)
        counter += 1
    visualize_ners.render_chapter(0, name + '_all', all_characters)
    rnd = str(random.random())
    return render_template('analyze.html', rnd=rnd, output=name, counter=counter, aura=aura)
项目:sel    作者:tiagoamartins    | 项目源码 | 文件源码
def uploader():
    if request.method == 'POST':
        f = request.files['file']
        f.save(secure_filename(f.filename))
        return 'file uploaded successfully'
项目:scoring-pipelines    作者:trustedanalytics    | 项目源码 | 文件源码
def upload_file():
    import tasks
    print('Uploading File Request')
    if tasks.uploaded == False:
        if request.method == 'POST':
            file = request.files['file']
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(os.getcwd(), filename))
                _extract_and_install(filename, True)
                tasks.uploaded = True
                return make_response("Uploaded file", 200)
    else:
    return make_response("Cannot upload another file as the Scoring Pipeline has already been initialized", 500)
项目:python-fav-memes-rest-api    作者:tomkowz    | 项目源码 | 文件源码
def _save_file_to_uploads(file):
        if file and MemeUploader._allowed_file(file.filename):
            # Save file
            original_filename = secure_filename(file.filename)
            ext = original_filename.split('.')[1]
            filename = str(uuid.uuid4()) + '.' + ext

            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return filename
        return None
项目:abstract-poetry    作者:Mebsworth    | 项目源码 | 文件源码
def upload():
    global tags
    tags = None
    if request.method == 'POST':
        file = request.files['image']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            print(filename)
            return redirect(url_for('view_uploaded_file', filename=filename))
    return render_template('upload.html')
项目:knowledge-repo    作者:airbnb    | 项目源码 | 文件源码
def file_upload():
    """ Uploads images dropped on the web editor's markdown box to static/images
        and notifies editors by email
    """
    upload_folder = 'images'
    title = request.form['title']
    files = request.files
    uploadedFiles = []

    if files:
        for img_file in files.values():
            filename = secure_filename(title + "_" + img_file.filename).lower()
            dst_folder = os.path.join(current_app.static_folder, upload_folder)

            if is_allowed_image_format(img_file):
                try:
                    img_file.save(os.path.join(dst_folder, filename))
                    send_from_directory(dst_folder, filename)
                    uploadedFiles += [url_for("static", filename=os.path.join(upload_folder, filename))]
                except Exception as e:
                    error_msg = u"ERROR during image upload: {}".format(str(e))
                    logger.error(error_msg)
                    return json.dumps({'error_msg': error_msg, 'success': False})

            elif is_pdf(filename):
                from PyPDF2 import PdfFileReader
                try:
                    src_pdf = PdfFileReader(img_file)
                    filename = os.path.splitext(filename)[0]
                    num_pages = src_pdf.getNumPages()
                    for page_num in range(num_pages):
                        page_png = pdf_page_to_png(src_pdf, page_num)
                        page_name = u"{filename}_{page_num}.jpg".format(**locals())
                        page_png.save(filename=os.path.join(dst_folder, page_name))
                        uploadedFiles += [url_for("static", filename=os.path.join(upload_folder, page_name))]
                except Exception as e:
                    error_msg = u"ERROR during pdf upload: {}".format(str(e))
                    logger.error(error_msg)
                    return json.dumps({'error_msg': error_msg, 'success': False})

    return json.dumps({'links': uploadedFiles, 'success': True})
项目:flux_line_bot    作者:blesscat    | 项目源码 | 文件源码
def upload_file():
    if request.method == 'GET':
        return render_template('upload_file.html')

    if request.method == 'POST':
        if bool(request.files):
            if os.environ['passed'] != "True":
                return "Methods is not allowed."
            file = request.files['file']
            if file.filename == '':
                return "File cannot be empty."
            if file and allowed_file(file.filename, 'fc'):
                filename = secure_filename(file.filename)
                file_path = os.path.join(app.config['FC_UPLOAD_FOLDER'],
                                         filename)
                file.save(file_path)
                try:
                    Flux = robot()
                except:
                    return 'FLUX connection temporarily not available.'
                Flux.upload_file(file_path, '/SD/Recent/webUpload.fc',
                                 process_callback=upload_callback)
                Flux.select_file('/SD/Recent/webUpload.fc')
                Flux.start_play()
                Flux.close()
                os.environ['passed'] = "False"
                while os.environ['passed'] != "False":
                    time.sleep(0.1)
                return 'success'
            else:
                return "File type must is fc."

        elif bool(request.form):
            password = request.form['password']
            if password != os.environ['password']:
                return "password is different from FLUX's."
            os.environ['passed'] = "True"
            while os.environ['passed'] != "True":
                time.sleep(0.1)
            return 'passed'
项目:Python_Homework    作者:yuyilei    | 项目源码 | 文件源码
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        print (str(file.filename))
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            file_url = url_for('uploaded_file', filename=filename)
            return html + '<br><img src=' + file_url + '>'
    return html
项目:amoc-project    作者:ajayns    | 项目源码 | 文件源码
def upload_file():
  f = request.files['file']
  f.save(secure_filename('1'))
  return "uploaded"
项目:the-catalog    作者:thurstonemerson    | 项目源码 | 文件源码
def uploadFileToServer(uploadFile, musicItem):
    filename = secure_filename(uploadFile.filename)
    uploadFile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return filename

#API Routes
项目:tensorflow_web_deploy    作者:hetaoaoao    | 项目源码 | 文件源码
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)
        path, extension = os.path.splitext(filename)
        if extension == '.png':
            im = Image.open(filename)
            filename = "%s.jpg" % path
            im.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.')
        )

    names, probs, time_cost, accuracy = app.clf.classify_image(
        open(os.path.join(filename), "rb").read())
    return flask.render_template(
        'index.html', has_result=True, result=[True, zip(names, probs), '%.3f' % time_cost],
        imagesrc=embed_image_html(image)
    )
项目:MultiFileUploadServer    作者:hust201010701    | 项目源码 | 文件源码
def upload_file():
    if request.method=='POST':
        for k in request.files:
            file = request.files[k]
            print(file)
            image_urls = []
            if file and allowed_file(file.filename):
                filename=secure_filename(file.filename)
                file.save(os.path.join(app.config['IMAGE_FOLDER'],filename))
                image_urls.append("images/%s"%filename)
        return jsonify({"code":1,"image_urls":image_urls})

#????????????????static???????
项目:ActivityManager    作者:yichengchen    | 项目源码 | 文件源码
def upload(activity, act, current_user):
    form = Forms.UploadFile()
    filename = None
    if form.validate_on_submit():
        ext_name = secure_filename(form.works.data.filename).split('.')[-1]

        print(current_user.name)

        filename = "{}_{}_{}.{}".format(act.title, current_user.stu_code, current_user.name, ext_name)
        # try:
        directory = 'uploads/{}/'.format(activity)
        if not os.path.exists(directory):
            os.makedirs(directory)
        print(filename)
        form.works.data.save(directory + filename)
        file_size = "{0}k".format(os.path.getsize(directory + filename) / 1000)

        data = UploadHistory(current_user.sid, activity, file_size)
        db.session.add(data)
        db.session.commit()
        # except Exception as err:
            # flash("??:" + str(err))
            # return jsonify(success=False,status="??:" + str(err))
        print("flash upload success")
        return jsonify(success=True,status="????!")
        # flash("????!", 'info')
    else:
        if request.method == "POST":
            return jsonify(success=False,status="????????????????????????")
            # print("validdate fail")
            # flash("validdate fail")
    last_time = UploadHistory.query.filter_by(sid=current_user.sid, activity=activity).order_by(UploadHistory.fid.desc()
                                                                                                ).first()

    if not last_time:
        last_time_msg = '???????'
    else:
        last_time_msg = '??????: {0} , ??: {1}'.format(last_time.time[:-7], last_time.size)

    return render_template('upload.html', user=current_user, form=form, filename=filename, l_s_m=last_time_msg, act=act)