Python上传附件 flask.request.files()

The following are 50 code examples for showing how to use flask.request.files(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

 

+ Save to library

Example 1

Project: OMW   Author: globalwordnet   File: wn_syntax.py View Source Project 10 votes vote downvote up
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 

 

Example 2

Project: aws-greengrass-mini-fulfillment   Author: awslabs   File: web.py View Source Project 8 votes vote downvote up
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 

 

Example 3

Project: NotHotDog   Author: ryanml   File: nothotdog.py View Source Project 7 votes vote downvote up
def is_hot_dog():
    if request.method == 'POST':
        if not 'file' in request.files:
            return jsonify({'error': 'no file'}), 400
        # Image info
        img_file = request.files.get('file')
        img_name = img_file.filename
        mimetype = img_file.content_type
        # Return an error if not a valid mimetype
        if not mimetype in valid_mimetypes:
            return jsonify({'error': 'bad-type'})
        # Write image to static directory and do the hot dog check
        img_file.save(os.path.join(app.config['UPLOAD_FOLDER'], img_name))
        hot_dog_conf = rekognizer.get_confidence(img_name)
        # Delete image when done with analysis
        os.remove(os.path.join(app.config['UPLOAD_FOLDER'], img_name))
        is_hot_dog = 'false' if hot_dog_conf == 0 else 'true'
        return_packet = {
            'is_hot_dog': is_hot_dog,
            'confidence': hot_dog_conf
        }
        return jsonify(return_packet) 

 

Example 4

Project: BookLibrary   Author: hufan-akari   File: views.py View Source Project 7 votes vote downvote up
def avatar(user_id):
    if current_user.id == user_id or current_user.can(Permission.UPDATE_OTHERS_INFORMATION):
        the_user = User.query.get_or_404(user_id)
        avatar_edit_form = AvatarEditForm()
        avatar_upload_form = AvatarUploadForm()
        if avatar_upload_form.validate_on_submit():
            if 'avatar' in request.files:
                forder = str(user_id)
                avatar_name = avatars.save(avatar_upload_form.avatar.data, folder=forder)
                the_user.avatar = json.dumps({"use_out_url": False, "url": avatar_name})
                db.session.add(the_user)
                db.session.commit()
                flash(u'??????!', 'success')
                return redirect(url_for('user.detail', user_id=user_id))
        if avatar_edit_form.validate_on_submit():
            the_user.avatar = json.dumps({"use_out_url": True, "url": avatar_edit_form.avatar_url.data})
            db.session.add(the_user)
            db.session.commit()
            return redirect(url_for('user.detail', user_id=user_id))
        return render_template('avatar_edit.html', user=the_user, avatar_edit_form=avatar_edit_form,
                               avatar_upload_form=avatar_upload_form, title=u"????")
    else:
        abort(403) 

Example 5

Project: microcosm-flask   Author: globality-corp   File: upload.py View Source Project 7 votes vote downvote up
def temporary_upload(name, fileobj):
    """
    Upload a file to a temporary location.

    Flask will not load sufficiently large files into memory, so it
    makes sense to always load files into a temporary directory.

    """
    tempdir = mkdtemp()
    filename = secure_filename(fileobj.filename)
    filepath = join(tempdir, filename)
    fileobj.save(filepath)
    try:
        yield name, filepath, fileobj.filename
    finally:
        rmtree(tempdir) 

Example 6

Project: deep-instrument-heroku   Author: bzamecnik   File: main.py View Source Project 7 votes vote downvote up
def classify():
    if 'audio_file' not in request.files:
        return redirect('/')

    # File-like object than can be directy passed to soundfile.read()
    # without saving to disk.
    audio_file = request.files['audio_file']

    if audio_file.filename == '':
        return redirect('/')

    class_probabilities = model.predict_probabilities(audio_file)
    class_probabilities = class_probabilities.round(5)
    label = model.class_label_from_probabilities(
        class_probabilities)

    return render_template('home.html',
        model_id=model_id,
        example_files=example_files,
        audio_file=audio_file.filename,
        predicted_label=label,
        class_probabilities=class_probabilities) 

 

Example 7

Project: nthu-ee-progreport-autogen   Author: HW-Lee   File: app.py View Source Project 7 votes vote downvote up
def post_file():
    if "var.json" in request.files.keys():
        usrvar = json.load(request.files["var.json"])
    else:
        return make_response("no var.json", 200)

    if "data.csv" in request.files.keys():
        csvfile = request.files["data.csv"]

        resp = { "server-connected": False, "data-posted": False, "err-occur": False }
        rpmng = ReportManager(usrvar)
        try:
            if rpmng.connect_server(): 
                resp["server-connected"] = True
                if rpmng.submit_progress(csvfile=csvfile): resp["data-posted"] = True

        except:
            resp["err-occur"] = True

        rpmng.finalize()

        return make_response(jsonify(resp), 200)
        
    else:
        return make_response("no data.csv", 200) 

Example 8

Project: autolipsync   Author: evgenijkatunov   File: main.py View Source Project 7 votes vote downvote up
def post_phonemes():
    print(request.files)
    if 'wave' not in request.files:
        abort(400)
    file = request.files['wave']
    tf = tempfile.NamedTemporaryFile(dir=UPLOAD_FOLDER)
    tmp_filename = tf.name
    tf.close()
    file.save(tmp_filename)
    wave = Wave()
    wave.load(tmp_filename)
    recogn = PhonemeRecognition()
    recogn.load('model_en_full')
    recogn.predict(wave)
    result = {'phonemes': wave.get_phoneme_map()}
    print(result)
    return json.dumps(result) 

Example 9

Project: python-ares   Author: pynog   File: report.py View Source Project 7 votes vote downvote up
def getAuthorizedFiles(fileConfigs, reportObj, report_name, userDirectory, fnct=None, ajax=False):
  ALIAS, DISK_NAME = 0, 1
  SQL_CONFIG = os.path.join(current_app.config['ROOT_PATH'], config.ARES_SQLITE_FILES_LOCATION)
  sqlFileDict = {'data': 'get_file_auth.sql', 'static': 'static_file_map.sql'}
  fileNameToParser = {}
  for fileConfig in fileConfigs:
    queryFileAuthPrm = {'team': session['TEAM'], 'file_cod': fileConfig['filename'], 'username': current_user.email, 'type': fileConfig.get('folder')}
    files = executeSelectQuery(os.path.join(current_app.config['ROOT_PATH'], config.ARES_USERS_LOCATION, report_name, 'db', 'admin.db'),
      open(os.path.join(SQL_CONFIG, sqlFileDict.get(fileConfig.get('folder')))).read(), params=queryFileAuthPrm)
    for file in files:
      if fileConfig.get('parser', None):
        reportObj.files[file[DISK_NAME]] = fileConfig['parser'](open(os.path.join(userDirectory, fileConfig['folder'], file[DISK_NAME])))
      elif fileConfig.get('type') == 'pandas':
        reportObj.files[file[DISK_NAME]] = os.path.join(userDirectory, fileConfig['folder'], file[DISK_NAME])
      else:
        reportObj.files[file[DISK_NAME]] = open(os.path.join(userDirectory, fileConfig['folder'], file[DISK_NAME]))
      if not ajax:
        fileNameToParser[file[DISK_NAME]] = "%s.%s" % (fileConfig['parser'].__module__.split(".")[-1], fileConfig['parser'].__name__)
      if fnct == 'params' and not ajax:
        reportObj.fileMap.setdefault(file[ALIAS], []).append(file[DISK_NAME])
  return fileNameToParser 

Example 10

Project: python-ares   Author: pynog   File: report.py View Source Project 7 votes vote downvote up
def deployment():
  """
  """
  hasFiles = False
  if request.files.getlist('file')[0]:
    hasFiles = True
  DATA = {'files': list(zip(request.files.getlist('file'), request.form.getlist('File Type'), request.form.getlist('file_code')))}
  for file, fileType, fileCod in DATA['files']:
    if fileType in ['static', 'data'] and not fileCod:
      return json.dumps('Error - You should specify a file code for statics and outputs'), 500

  env = request.values['env']
  isNew = True if request.values['isNew'] == 'true' else False
  if isNew:
    createEnv(env)
  if hasFiles:
    return deployFiles(env, DATA)

  return json.dumps("Environment created"), 200 

Example 11

Project: python-ares   Author: pynog   File: report.py View Source Project 7 votes vote downvote up
def getAresFilesVersions():
  """ Return the files, the version and the size """
  aresModulePath = os.path.join(current_app.config['ROOT_PATH'], config.ARES_FOLDER, 'Lib')
  files = {}
  for pyFile in os.listdir(aresModulePath):
    if Ares.isExcluded(current_app.config['ROOT_PATH'], file=pyFile):
      continue

    stat = os.stat(os.path.join(aresModulePath, pyFile))
    files[pyFile] = [stat.st_mtime, stat.st_size]
  # Add all the external libraries
  libPath = os.path.join(current_app.config['ROOT_PATH'], 'Lib')
  for (path, dirs, f) in os.walk(libPath):
    for pyFile in  f:
      if Ares.isExcluded(current_app.config['ROOT_PATH'], file=pyFile):
        continue

      stat = os.stat(os.path.join(libPath, pyFile))
      files[pyFile] = [stat.st_mtime, stat.st_size]
  return json.dumps(files) 

Example 12

Project: WebAppEx   Author: karlafej   File: view.py View Source Project 7 votes vote downvote up
def index():
    form1 = InputFile(request.form)
    form2 = InputLim(request.form)

    if form2.limit.data:
        session['limit'] = int(form2.limit.data)
    else: session['limit'] = 500

    if form1.submit1.data :
        txt = request.files[form1.textfile.name].read()
        txt=str(txt.decode("utf-8"))
        txt=regex.sub(" ", txt).lower() 
        if len(txt)>0 :
            session['text'] = txt
        	
    if 'text' in session:
        result = get_plot(session['limit'], session['text'])       
    else:
        result = None
        
    return render_template('view.html', form1=form1, form2 = form2, result=result) 

Example 13

Project: kuberdock-platform   Author: cloudlinux   File: predefined_apps.py View Source Project 7 votes vote downvote up
def _take_template_from_uploads_if_needed(fn):
    """Takes template from request.files if 'template' from **kwargs is empty.
    Must be called before @use_kwargs.
    """

    @wraps(fn)
    def wrapper(*args, **kwargs):
        template = kwargs.get('template')
        if template is None:
            template = request.files.to_dict().get('template')
            if template is not None:
                template = template.stream.read()
        kwargs['template'] = template
        return fn(*args, **kwargs)

    return wrapper 

Example 14

Project: fame   Author: certsocietegenerale   File: files.py View Source Project 7 votes vote downvote up
def index(self):
        """Get the list of objects.

        .. :quickref: File; Get the list of objects

        Response is paginated and will only contain 25 results. The most recent
        objects appear first.

        :query page: page number.
        :type page: int

        :>json list files: list of files (see :http:get:`/files/(id)` for details on the format of a file).
        """
        page = int(request.args.get('page', 1))

        files = current_user.files.find().sort('_id', DESCENDING).limit(PER_PAGE).skip((page - 1) * PER_PAGE)
        pagination = Pagination(page=page, per_page=PER_PAGE, total=files.count(), css_framework='bootstrap3')
        files = {'files': clean_files(list(files))}

        return render(files, 'files/index.html', ctx={'data': files, 'pagination': pagination}) 

Example 15

Project: fame   Author: certsocietegenerale   File: files.py View Source Project 7 votes vote downvote up
def get(self, id):
        """Get the object with `id`.

        .. :quickref: File; Get an object

        Resulting object is in the ``file`` field.

        :param id: id of the object.

        :>json dict _id: ObjectId dict.
        :>json string md5: MD5 hash.
        :>json string sha1: SHA1 hash.
        :>json string sha256: SHA256 hash.
        :>json string type: FAME type.
        :>json string mime: mime type.
        :>json string detailed_type: detailed type.
        :>json list groups: list of groups (as strings) that have access to this file.
        :>json list owners: list of groups (as strings) that submitted this file.
        :>json list probable_names: list of probable names (as strings).
        :>json list analysis: list of analyses' ObjectIds.
        :>json list parent_analyses: list of analyses (as ObjectIds) that extracted this object.
        :>json dict antivirus: dict with antivirus names as keys.
        """
        file = {'file': clean_files(get_or_404(current_user.files, _id=id))}
        return return_file(file) 

Example 16

Project: fame   Author: certsocietegenerale   File: files.py View Source Project 7 votes vote downvote up
def submit_to_av(self, id, module):
        """Submit a file to an Antivirus module.

        .. :quickref: File; Submit file to an antivirus module

        If succesful, the response will be ``"ok"``. Otherwise, it will be an
        error message.

        :param id: id of the file to submit.
        :param module: name of the module to submit the file to.
        """
        f = File(get_or_404(current_user.files, _id=id))

        for av_module in dispatcher.get_antivirus_modules():
            if av_module.name == module:
                av_module.submit(f['filepath'])
                f.update_value(['antivirus', module], True)
                break
        else:
            return make_response("antivirus module '{}' not present / enabled.".format(module))

        return make_response("ok") 

Example 17

Project: anti-captcha.shuosc.org   Author: shuopensourcecommunity   File: app.py View Source Project 7 votes vote downvote up
def jwc():
    response = {'succeed': 0}
    try:
        captcha_file = request.files['captcha']
    except Exception as e:
        response['reason'] = "cannot fetch the image file, please post it with key 'captcha'."
        return json.dumps(response)

    if not allowed_file(captcha_file.filename):
        response['reason'] = "this file type is no supported."
        return json.dumps(response)

    try:
        im = Image.open(captcha_file)
        predict = solve_jwc(im)
    except Exception as e:
        response['reason'] = "an error occurred: %s" % str(e)
    else:
        response['succeed'] = 1
        response['result'] = predict
    return json.dumps(response) 

Example 18

Project: web_develop   Author: dongweiming   File: app.py View Source Project 7 votes vote downvote up
def j():
    uploaded_file = request.files['file']

    if uploaded_file:
        paste_file = PasteFile.create_by_upload_file(uploaded_file)
        db.session.add(paste_file)
        db.session.commit()
        width, height = paste_file.image_size

        return jsonify({
            'url': paste_file.url_i,
            'short_url': paste_file.url_s,
            'origin_filename': paste_file.filename,
            'hash': paste_file.filehash,
            'width': width,
            'height': height
        })

    return abort(400) 

Example 19

Project: Cuneiform   Author: nervouna   File: __init__.py View Source Project 6 votes vote downvote up
def create_post():

    post_data = {
        'title': request.form.get('title'),
        'content': request.form.get('content'),
    }
    post = Post()
    post.set(post_data)
    post = markdown(post)

    upload_image = request.files.get('featured_image')
    if upload_image.filename != '' and allowed_file(upload_image.filename):
        f = Attachment(upload_image.filename, data=upload_image.stream)
        post.set('featured_image', f)

    post.save()

    tag_names = request.form.get('tags').lower().strip()
    tags = [get_tag_by_name(x) for x in split_tag_names(tag_names)]
    map_tags_to_post(tags, post)

    return redirect(url_for('show_post', post_id=post.id)) 

Example 20

Project: pokedex-as-it-should-be   Author: leotok   File: app.py View Source Project 6 votes vote downvote up
def predict():
    import ipdb; ipdb.set_trace(context=20)
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    
    if file.filename == '':
        flash('No selected file')
        return redirect(request.url)
    
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        try:
            pokemon_name = predict_mlp(file).capitalize()
            pokemon_desc = pokemon_entries.get(pokemon_name)
            msg = ""
        except Exception as e:
            pokemon_name = None
            pokemon_desc = None
            msg = str(e)

    return jsonify({'name': pokemon_name, 'description': pokemon_desc, "msg": msg}) 

Example 21

Project: anti-captcha.shuosc.org   Author: shuopensourcecommunity   File: app.py View Source Project 6 votes vote downvote up
def phylab():
    response = {'succeed': 0}
    try:
        captcha_file = request.files['captcha']
    except Exception as e:
        response['reason'] = "cannot fetch the image file, please post it with key 'captcha'."
        return json.dumps(response)

    if not allowed_file(captcha_file.filename):
        response['reason'] = "this file type is no supported."
        return json.dumps(response)

    try:
        im = Image.open(captcha_file)
        predict = solve_phylab(im)
    except Exception as e:
        response['reason'] = "an error occurred: %s" % str(e)
    else:
        response['succeed'] = 1
        response['result'] = predict
    return json.dumps(response) 

Example 22

Project: anti-captcha.shuosc.org   Author: shuopensourcecommunity   File: app.py View Source Project 6 votes vote downvote up
def xgb():
    response = {'succeed': 0}
    try:
        captcha_file = request.files['captcha']
    except Exception as e:
        response['reason'] = "cannot fetch the image file, please post it with key 'captcha'."
        return json.dumps(response)

    if not allowed_file(captcha_file.filename):
        response['reason'] = "this file type is no supported."
        return json.dumps(response)

    try:
        filename = time.time()
        captcha_file.save("tmp/%s" % (str(filename)))
        cmd = "tesseract tmp/%s stdout" % (filename)
        predict = str(os.popen(cmd).read().strip('\n'))

        os.popen("mv tmp/%s tmp/%s" % (str(filename), "".join([str(filename), "_", predict])))
    except Exception as e:
        response['reason'] = "an error occurred: %s" % str(e)
    else:
        response['succeed'] = 1
        response['result'] = predict
    return json.dumps(response) 

Example 23

Project: web_develop   Author: dongweiming   File: app.py View Source Project 6 votes vote downvote up
def j():
    uploaded_file = request.files['file']

    if uploaded_file:
        rs = create(uploaded_file)
        if rs['r']:
            return rs['error']

        paste_file = rs['paste_file']

        width, height = paste_file.image_size

        return jsonify({
            'url': paste_file.url_i,
            'short_url': paste_file.url_s,
            'origin_filename': paste_file.filename,
            'hash': paste_file.filehash,
            'width': width,
            'height': height
        })

    return abort(400) 

Example 24

Project: web_develop   Author: dongweiming   File: app.py View Source Project 6 votes vote downvote up
def j():
    uploaded_file = request.files['file']

    if uploaded_file:
        paste_file = PasteFile.create_by_upload_file(uploaded_file)
        db.session.add(paste_file)
        db.session.commit()
        width, height = paste_file.image_size

        return jsonify({
            'url': paste_file.url_i,
            'short_url': paste_file.url_s,
            'origin_filename': paste_file.filename,
            'hash': paste_file.filehash,
            'width': width,
            'height': height
        })

    return abort(400) 

Example 25

Project: web_develop   Author: dongweiming   File: app.py View Source Project 6 votes vote downvote up
def j():
    uploaded_file = request.files['file']

    if uploaded_file:
        paste_file = PasteFile.create_by_upload_file(uploaded_file)
        paste_file.save()
        width, height = paste_file.image_size

        return jsonify({
            'url': paste_file.url_i,
            'short_url': paste_file.url_s,
            'origin_filename': paste_file.filename,
            'hash': paste_file.filehash,
            'width': width,
            'height': height
        })

    return abort(400) 

Example 26

Project: son-emu   Author: sonata-nfv   File: dummygatekeeper.py View Source Project 6 votes vote downvote up
def onboard(self):
        """
        Do all steps to prepare this service to be instantiated
        :return:
        """
        # 1. extract the contents of the package and store them in our catalog
        self._unpack_service_package()
        # 2. read in all descriptor files
        self._load_package_descriptor()
        self._load_nsd()
        self._load_vnfd()
        if DEPLOY_SAP:
            self._load_saps()
        # 3. prepare container images (e.g. download or build Dockerfile)
        if BUILD_DOCKERFILE:
            self._load_docker_files()
            self._build_images_from_dockerfiles()
        else:
            self._load_docker_urls()
            self._pull_predefined_dockerimages()
        LOG.info("On-boarded service: %r" % self.manifest.get("name")) 

Example 27

Project: son-emu   Author: sonata-nfv   File: dummygatekeeper.py View Source Project 6 votes vote downvote up
def _load_vnfd(self):
        """
        Load all VNFD YAML files referenced in MANIFEST.MF and keep them in dict.
        :return:
        """

        # first make a list of all the vnfds in the package
        vnfd_set = dict()
        if "package_content" in self.manifest:
            for pc in self.manifest.get("package_content"):
                if pc.get("content-type") == "application/sonata.function_descriptor":
                    vnfd_path = os.path.join(
                        self.package_content_path,
                        make_relative_path(pc.get("name")))
                    vnfd = load_yaml(vnfd_path)
                    vnfd_set[vnfd.get("name")] = vnfd
            # then link each vnf_id in the nsd to its vnfd
            for  vnf_id in self.vnf_id2vnf_name:
                vnf_name = self.vnf_id2vnf_name[vnf_id]
                self.vnfds[vnf_id] = vnfd_set[vnf_name]
                LOG.debug("Loaded VNFD: {0} id: {1}".format(vnf_name, vnf_id)) 

Example 28

Project: nftablui   Author: larsbs   File: files.py View Source Project 6 votes vote downvote up
def restore_backup():
    '''
    POST:
      Receive a backup file and load it into the system
    '''
    with tempfile.NamedTemporaryFile(suffix='.nft', delete=False) as tf:
        backup = request.files['file'].read()
        tf.write(backup)
    cmd = nft_utils.nft_command('-f ' + tf.name)
    cmd_result = cmd.wait()
    if cmd_result == 0:
        nft_utils.close_nft_command(cmd)
        os.remove(tf.name)
        return make_response('Backup restored')
    else:
        return abort(500, NFTError(Error(cmd.stdout.read()))) 

Example 29

Project: suricatest   Author: 0x00ach   File: worker.py View Source Project 6 votes vote downvote up
def new_analysis():
    analysis_pcap = None
    analysis_title = None
    analysis_ruleset = None
    pcap_name = None
    pcap_path = None
    if "title" in request.form:
        analysis_title = request.form["title"]
    if "pcap" in request.files:
        analysis_pcap = request.files["pcap"]
    if "ruleset" in request.form:
        analysis_ruleset = request.form["ruleset"]
    if analysis_pcap is None:
        return render_template("index.html", analyses = db_handler.search_analyses())
    pcap_name = analysis_pcap.filename
    pcap_name = secure_filename(str(int(time.time()))+"_"+hashlib.sha256(pcap_name).hexdigest()+".pcap")
    pcap_path = os.path.join(storage_folder, pcap_name)
    analysis_pcap.save(pcap_path)
    x = analysis_handler(pcap_file=pcap_path, ruleset=analysis_ruleset, pcap_name=pcap_name, title=analysis_title)
    analysis_pool.add_analysis(x)
    return render_template("index.html", analyses=db_handler.search_analyses()) 

Example 30

Project: suricatest   Author: 0x00ach   File: worker.py View Source Project 6 votes vote downvote up
def api_new_analysis():
    analysis_pcap = None
    analysis_title = None
    analysis_ruleset = None
    pcap_name = None
    pcap_path = None
    if "title" in request.form:
        analysis_title = request.form["title"]
    if "pcap" in request.files:
        analysis_pcap = request.files["pcap"]
    if "ruleset" in request.form:
        analysis_ruleset = request.form["ruleset"]
    if analysis_pcap is None:
        return "{'id':0}"
    pcap_name = analysis_pcap.filename
    pcap_name = secure_filename(str(int(time.time()))+"_"+hashlib.sha256(pcap_name).hexdigest()+".pcap")
    pcap_path = os.path.join(storage_folder, pcap_name)
    analysis_pcap.save(pcap_path)
    x = analysis_handler(pcap_file=pcap_path, ruleset=analysis_ruleset, pcap_name=pcap_name, title=analysis_title)
    analysis_pool.add_analysis(x)
    return json.dumps({"id":x.analysis_id}) 

Example 31

Project: budgettracker   Author: maximebf   File: __init__.py View Source Project 6 votes vote downvote up
def update(year, month):
    date = datetime.date(year, month, 1)
    filename = None
    delete_file = False
    if bank_adapter.fetch_type == 'file':
        if 'file' not in request.files:
            abort(400)
        file = request.files['file']
        if config.get('imports_dir'):
            filename = os.path.join(config['imports_dir'],
                '%s-%s' % (datetime.date.today().isoformat(), secure_filename(file.filename)))
            if not os.path.exists(os.path.dirname(filename)):
                os.makedirs(os.path.dirname(filename))
        else:
            temp_file = NamedTemporaryFile(delete=False)
            filename = temp_file.name
            temp_file.close()
            delete_file = True
        file.save(filename)
    update_local_data(config, date=date, filename=filename, storage=storage)
    if delete_file:
        os.unlink(filename)
    return redirect(url_for('index', year=year, month=month)) 

Example 32

Project: blcf   Author: willard-yuan   File: app.py View Source Project 6 votes vote downvote up
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 

Example 33

Project: duckpond   Author: alexmilowski   File: api.py View Source Project 6 votes vote downvote up
def content_item_resource_upload(id,property):
   #print(request.headers['Content-Type'])
   #print(request.files)
   file = request.files['file']
   #print(file.filename)
   #print(file.content_type)
   #print(file.content_length)
   uploadContentType = file.content_type
   if file.content_type.startswith("text/") and file.content_type.find("charset=")<0:
      uploadContentType = file.content_type+"; charset=UTF-8"
   uploadDir = app.config['UPLOAD_STAGING'] if 'UPLOAD_STAGING' in app.config else 'tmp'
   os.makedirs(uploadDir,exist_ok=True)
   staged = os.path.join(uploadDir, file.filename)
   file.save(staged)
   status = 500
   responseJSON = None
   contentType = None
   with open(staged,"rb") as data:
      status,responseJSON,contentType = model.uploadContentResource(id,property,file.filename,uploadContentType,os.path.getsize(staged),data)
   os.unlink(staged)
   if status==200 or status==201:
      return Response(stream_with_context(responseJSON),status=status,content_type = contentType)
   else:
      return Response(status=status) 

Example 34

Project: flask-nsfw   Author: smitthakkar96   File: flask_nsfw.py View Source Project 6 votes vote downvote up
def block(self):
        """
            block is a decorator function that wraps around the route and does all the crazy stuff
        """
        def decorator(func):
            @wraps(func)
            def wrapped():
                if request.method == 'POST' or request.method == 'PUT':
                    result = True
                    result2 = True
                    if request.form:
                        result2 = self.collect_urls(request.form.values())
                    if request.files:
                        result = self.test_files_against_api(
                            request.files.values())
                    elif request.json:
                        result = self.test_base64_data(request.json.values())
                        result2 = self.collect_urls(request.json.values())
                    if not result or not result2:
                        return jsonify({"response": "seems like the request contains the" \
                                        + " images that contains NSFW content."}), 403
                return func()
            return wrapped
        return decorator 

Example 35

Project: tfserving_predict_client   Author: epigramai   File: mnist_example.py View Source Project 6 votes vote downvote up
def predict():
    logger.info('/predict, hostname: ' + str(socket.gethostname()))

    if 'image' not in request.files:
        logger.info('Missing image parameter')
        return Response('Missing image parameter', 400)

    # Write image to disk
    with open('request.png', 'wb') as f:
        f.write(request.files['image'].read())

    img = cv2.imread('request.png', 0)
    img = np.resize(img, (28, 28, 1))

    ''' Return value will be None if model not running on host '''
    prediction = mnist_client.predict(np.array([img]))

    logger.info('Prediction of length: ' + str(len(prediction)))

    ''' Convert the dict to json and return response '''
    return jsonify(
        prediction=prediction,
        prediction_length=len(prediction),
        hostname=str(socket.gethostname())
    ) 

Example 36

Project: tfserving_predict_client   Author: epigramai   File: mnist_mock_client_example.py View Source Project 6 votes vote downvote up
def predict():
    logger.info('/predict, hostname: ' + str(socket.gethostname()))

    if 'image' not in request.files:
        logger.info('Missing image parameter')
        return Response('Missing image parameter', 400)

    # Write image to disk
    with open('request.png', 'wb') as f:
        f.write(request.files['image'].read())

    img = cv2.imread('request.png', 0)
    img = np.resize(img, (28, 28, 1))
    prediction = mnist_client.predict(np.array([img]))

    logger.info('Prediction of length:' + str(len(prediction)))

    ''' Convert the dict to json and return response '''
    return jsonify(
        prediction=prediction,
        prediction_length=len(prediction),
        hostname=str(socket.gethostname())
    ) 

Example 37

Project: cuckoodroid-2.0   Author: idanr1986   File: api.py View Source Project 6 votes vote downvote up
def pcap_get(task_id):
    task = Task.query.get(task_id)
    if not task:
        return json_error(404, "Task not found")

    if task.status == Task.DELETED:
        return json_error(404, "Task files has been deleted")

    if task.status != Task.FINISHED:
        return json_error(420, "Task not finished yet")

    pcap_path = os.path.join(settings.reports_directory,
                             "%s" % task_id, "dump.pcap")
    if not os.path.isfile(pcap_path):
        return json_error(404, "Pcap file not found")

    return send_file(pcap_path) 

Example 38

Project: cuckoodroid-2.0   Author: idanr1986   File: api.py View Source Project 6 votes vote downvote up
def memorydumps_list(task_id):
    folder_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", str(task_id), "memory")

    if os.path.exists(folder_path):
        memory_files = []
        memory_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", str(task_id), "memory")
        for subdir, dirs, files in os.walk(memory_path):
            for filename in files:
                memory_files.append(filename.replace(".dmp", ""))

        if len(memory_files) == 0:
            return json_error(404, "Memory dump not found")

        return jsonify({"dump_files": memory_files})
    else:
        return json_error(404, "Memory dump not found") 

Example 39

Project: flask-app-for-mxnet-img-classifier   Author: XD-DENG   File: app.py View Source Project 6 votes vote downvote up
def FUN_upload_image():

    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return(redirect(url_for("FUN_root")))
        file = request.files['file']

        # if user does not select file, browser also submit a empty part without filename
        if file.filename == '':
            return(redirect(url_for("FUN_root")))

        if file and allowed_file(file.filename):
            filename = os.path.join("static/img_pool", hashlib.sha256(str(datetime.datetime.now())).hexdigest() + secure_filename(file.filename).lower())
            file.save(filename)
            prediction_result = mx_predict(filename, local=True)
	    FUN_resize_img(filename)
            return render_template("index.html", img_src = filename, prediction_result = prediction_result)
    return(redirect(url_for("FUN_root")))


################################################
# Start the service
################################################ 

Example 40

Project: Loxo   Author: JamesMilnerUK   File: loxoapi.py View Source Project 6 votes vote downvote up
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename, ALLOWED_EXTENSIONS):
            filename = secure_filename(file.filename)
            file_location = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            print "file location", file_location
            file.save(file_location)
            saved_file = url_for('uploaded_file', filename=filename)

            endpoint_name = os.path.splitext(filename)[0]
            database = request.form.get("database")
            if not database:
                print request.form["database"]
                raise InvalidUsage("Database name was not provided", 400, '{ "error" : "database was not provided" }')
            else:
                handle_file(database, file_location, endpoint_name, host)

            return redirect('/loxo/' + database + '/collections/' + endpoint_name)

    return render_template('upload.html') 

Example 41

Project: codenn   Author: sriniiyer   File: legacy.py View Source Project 6 votes vote downvote up
def _get_sql(data, files=None):
    sql = None
    if files is not None and 'datafile' in files:
        raw = files['datafile'].read()
        try:
            sql = raw.decode('utf-8')
        except UnicodeDecodeError, err:
            logging.error(err)
            logging.debug(repr(raw))
            sql = (u'-- UnicodeDecodeError: %s\n'
                   u'-- Please make sure to upload UTF-8 encoded data for now.\n'
                   u'-- If you want to help improving this part of the application\n'
                   u'-- please file a bug with some demo data at:\n'
                   u'-- http://code.google.com/p/python-sqlparse/issues/entry\n'
                   u'-- Thanks!\n' % err)
    if not sql:
        sql = data.get('data')
    return sql or '' 

Example 42

Project: im2txt_api   Author: mainyaa   File: run_inference.py View Source Project 6 votes vote downvote up
def upload():
  #pprint.pprint(request.files)

  # check if the post request has the file part
  if 'file' not in request.files:
    #print("not file")
    return redirect("/")
  file = request.files['file']
  # if user does not select file, browser also
  # submit a empty part without filename
  if file.filename == '':
    return redirect("/")
  filename = secure_filename(file.filename)
  path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
  file.save(path)
  FLAGS.input_files = path
  # inference
  result = main(None)
  #print(result)
  return jsonify(result) 

Example 43

Project: zou   Author: cgwire   File: resources.py View Source Project 6 votes vote downvote up
def get(self, instance_id):
        if not self.is_exist(instance_id):
            abort(404)

        if not self.is_allowed(instance_id):
            abort(403)

        folder_path = thumbnail_utils.get_preview_folder_name(
            self.subfolder,
            instance_id
        )
        file_name = thumbnail_utils.get_file_name(instance_id)

        # Use legacy folder name if the file cannot be found.
        if not os.path.exists(os.path.join(folder_path, file_name)):
            folder_path = thumbnail_utils.get_folder_name("preview-files")

        return send_from_directory(
            directory=folder_path,
            filename=file_name
        ) 

Example 44

Project: zou   Author: cgwire   File: resources.py View Source Project 6 votes vote downvote up
def post(self, instance_id):
        if not self.is_exist(instance_id):
            abort(404)

        self.check_permissions(instance_id)
        uploaded_file = request.files["file"]
        thumbnail_utils.save_file(
            self.data_type,
            instance_id,
            uploaded_file,
            size=self.size
        )

        thumbnail_url_path = \
            thumbnail_utils.url_path(
                self.data_type,
                instance_id
            )

        return {"thumbnail_path": thumbnail_url_path}, 201 

Example 45

Project: zou   Author: cgwire   File: base.py View Source Project 6 votes vote downvote up
def post(self):
        uploaded_file = request.files["file"]
        file_name = "%s.csv" % uuid.uuid4()

        file_path = os.path.join(app.config["TMP_DIR"], file_name)
        uploaded_file.save(file_path)
        result = []

        try:
            self.check_permissions()
            self.prepare_import()
            with open(file_path) as csvfile:
                reader = csv.DictReader(csvfile)
                for row in reader:
                    result.append(self.import_row(row))

            return fields.serialize_models(result), 201
        except KeyError as e:
            return {"error": "A column is missing: %s" % e}, 400
        except permissions.PermissionDenied:
            abort(403) 

Example 46

Project: OpenRPG   Author: jdsutton   File: gameServer.py View Source Project 6 votes vote downvote up
def addTileset(gameID):
    '''
        Create a tileset
    '''
    file = request.files['file']
    if file.filename == '':
        flash('No file selected')
    elif not file.filename.endswith('.png'):
        flash('Upload failed: file type must be .png')
    else:
        directory = GamesList.getByID(gameID).getTileDir()
        destination = os.path.join(directory, file.filename)
        file.save(destination)

    return redirect(url_for('GAMES_PATH_BLUEPRINT.editGame',
        gameID=gameID)) 

Example 47

Project: OpenRPG   Author: jdsutton   File: gameServer.py View Source Project 6 votes vote downvote up
def addProp(gameID):
    '''
        Upload a prop image
    '''
    file = request.files['file']
    if file.filename == '':
        flash('No file selected')
    elif not file.filename.endswith('.png'):
        flash('Upload failed: file type must be .png')
    else:
        directory = GamesList.getByID(gameID).getPropDir()
        destination = os.path.join(directory, file.filename)
        file.save(destination)
        flash('Prop added successfully')

    return redirect(url_for('GAMES_PATH_BLUEPRINT.editGame',
        gameID=gameID)) 

Example 48

Project: margy   Author: opentower   File: letters.py View Source Project 5 votes vote downvote up
def upload_letter():
    if request.method == 'POST':
        rfn = request.form['rec_fname'].lstrip().rstrip() #assigns input text to variables; this is Recommender's First Name
        rln = request.form['rec_lname'].lstrip().rstrip() #Recommender's Last Name
        afn = request.form['app_fname'].lstrip().rstrip() #Applicant's First Name
        aln = request.form['app_lname'].lstrip().rstrip() #Applicant's Last Name
        aem = request.form['app_email'].lstrip().rstrip() #Applicant's Email Address
        aec = request.form['app_emailc'].lstrip().rstrip() #Applicant's Email Address (confirmed)
        note = request.form['app_note'] #Optional note to applicant
        rfncode = rfn.replace(" ", "_") #Replaces spaces with underscores in names
        rlncode = rln.replace(" ", "_")
        afncode = afn.replace(" ", "_")
        alncode = aln.replace(" ", "_")
        codename = alncode + rlncode #Assigns Applicant's Last Name and Recommender's Last Name as the fist part of the letter's file name
        d = io.open('metadata.txt', 'r', encoding="utf-8")
        num = 0
        for line in d: #checks whether there are other lines in the metadata with the same Last Names combination
            if codename.lower() == line.rstrip().lower()[:len(codename)]:
                num += 1
        if num != 0: #if there are n instances of this particular Last Name Combination in the metadata and n > 0, appends the codename with n+1.
            codename += str(num)
        codedfilename = 'letters/' + codename + ".pdf" #assigns the file a path: letters/[value of codename].pdf
        metadata = codename + ' ' + rfncode + ' ' + rlncode + ' ' + afncode + ' ' + alncode + ' ' + aem + '\r\n' #creates a line of metadata from all the above
        f = request.files['letter']
        if f.mimetype != 'application/pdf': #displays an error if the uploaded file is not a PDF
            return render_template('failure.html')
        else:
            if aem != aec: #displays an error if the email addresses do not match
                return render_template('mismatch.html')
            else:
                key = f_encrypt(codedfilename, f.read()) #encrypts the letter and assigns it a decryption key
                mailto = codename + '_' + key #creates a mailto code, concatenating the codename, an underscore, and the key
                a = io.open('metadata.txt', 'a', encoding="utf-8")
                a.write(metadata) #writes the metadata to metadata.txt
                a.close()
                txtbody = render_template('rec_confirm.txt',rfn=rfn,rln=rln,afn=afn,aln=aln,aem=aem,codename=mailto,note=note)
                htmlbody = render_template('rec_confirm.html',rfn=rfn,rln=rln,afn=afn,aln=aln,aem=aem,codename=mailto,note=note)
                EmailUtils.rich_message('[email protected]',aem,'Letter Received',txtbody,htmlbody) #sends an email to the applicant with their mailto code
                savedas = codename + '.pdf'
                return render_template('success.html',aem=aem,codename=codename,savedas=savedas) #displays a success message to the uploader 

Example 49

Project: toll_road   Author: idosekely   File: toll_road.py View Source Project 5 votes vote downvote up
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" 

Example 50

Project: Flask_Blog   Author: sugarguo   File: views.py View Source Project 5 votes vote downvote up
def ckupload():
    #site_info = site_get()
    """CKEditor file upload"""
    error = ''
    url = ''
    callback = request.args.get("CKEditorFuncNum")

    if request.method == 'POST' and 'upload' in request.files:
        fileobj = request.files['upload']
        fname, fext = os.path.splitext(fileobj.filename)
        rnd_name = '%s%s' % (gen_rnd_filename(), fext)

        filepath = os.path.join(app.static_folder, 'upload', rnd_name)

        # ???????????????
        dirname = os.path.dirname(filepath)
        if not os.path.exists(dirname):
            try:
                os.makedirs(dirname)
            except:
                error = 'ERROR_CREATE_DIR'
        elif not os.access(dirname, os.W_OK):
            error = 'ERROR_DIR_NOT_WRITEABLE'

        if not error:
            fileobj.save(filepath)
            url = url_for('static', filename='%s/%s' % ('upload', rnd_name))
    else:
        error = 'post error'
    #print callback
    res = """""" % (callback, url, error)

    response = make_response(res)
    response.headers["Content-Type"] = "text/html"
    return response 

你可能感兴趣的:(Python)