python类files()的实例源码

app.py 文件源码 项目:blcf 作者: willard-yuan 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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
api.py 文件源码 项目:duckpond 作者: alexmilowski 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
flask_nsfw.py 文件源码 项目:flask-nsfw 作者: smitthakkar96 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
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
mnist_example.py 文件源码 项目:tfserving_predict_client 作者: epigramai 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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())
    )
mnist_mock_client_example.py 文件源码 项目:tfserving_predict_client 作者: epigramai 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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())
    )
api.py 文件源码 项目:cuckoodroid-2.0 作者: idanr1986 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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)
api.py 文件源码 项目:cuckoodroid-2.0 作者: idanr1986 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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")
app.py 文件源码 项目:flask-app-for-mxnet-img-classifier 作者: XD-DENG 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
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
################################################
loxoapi.py 文件源码 项目:Loxo 作者: JamesMilnerUK 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
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')
legacy.py 文件源码 项目:codenn 作者: sriniiyer 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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 ''
run_inference.py 文件源码 项目:im2txt_api 作者: mainyaa 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
resources.py 文件源码 项目:zou 作者: cgwire 项目源码 文件源码 阅读 48 收藏 0 点赞 0 评论 0
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
        )
resources.py 文件源码 项目:zou 作者: cgwire 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
base.py 文件源码 项目:zou 作者: cgwire 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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)
gameServer.py 文件源码 项目:OpenRPG 作者: jdsutton 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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))
gameServer.py 文件源码 项目:OpenRPG 作者: jdsutton 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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))
toll_road.py 文件源码 项目:toll_road 作者: idosekely 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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"
views.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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 = """<script type="text/javascript">
  window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');
</script>""" % (callback, url, error)

    response = make_response(res)
    response.headers["Content-Type"] = "text/html"
    return response
base.py 文件源码 项目:functest 作者: opnfv 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _post_args(self):  # pylint: disable=no-self-use
        # pylint: disable=maybe-no-member
        """ Return action and args after parsing request """

        data = request.json if request.json else {}
        params = api_utils.change_to_str_in_dict(data)
        action = params.get('action', request.form.get('action', ''))
        args = params.get('args', {})
        try:
            args['file'] = request.files['file']
        except KeyError:
            pass
        LOGGER.debug('Input args are: action: %s, args: %s', action, args)

        return action, args


问题


面经


文章

微信
公众号

扫码关注公众号