flask.request.files

Here are the examples of the python api flask.request.files taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

233 Examples 7

3 Source : views.py
with Apache License 2.0
from abhioncbr

    def varimport(self):
        try:
            d = json.load(UTF8_READER(request.files['file']))
        except Exception as e:
            flash("Missing file or syntax error: {}.".format(e))
        else:
            for k, v in d.items():
                models.Variable.set(k, v, serialize_json=isinstance(v, dict))
            flash("{} variable(s) successfully updated.".format(len(d)))
        return redirect('/admin/variable')


class HomeView(AdminIndexView):

3 Source : views.py
with Apache License 2.0
from abhioncbr

    def varimport(self):
        try:
            out = str(request.files['file'].read())
            d = json.loads(out)
        except Exception:
            flash("Missing file or syntax error.")
        else:
            for k, v in d.items():
                models.Variable.set(k, v, serialize_json=isinstance(v, dict))
            flash("{} variable(s) successfully updated.".format(len(d)))
        return redirect('/admin/variable')

class HomeView(AdminIndexView):

3 Source : views.py
with Apache License 2.0
from abhioncbr

    def varimport(self):
        try:
            out = str(request.files['file'].read())
            d = json.loads(out)
        except Exception:
            flash("Missing file or syntax error.")
        else:
            for k, v in d.items():
                models.Variable.set(k, v, serialize_json=isinstance(v, dict))
            flash("{} variable(s) successfully updated.".format(len(d)))
        return redirect('/admin/variable')


class HomeView(AdminIndexView):

3 Source : wsgi.py
with Apache License 2.0
from accessai

def parse():
    img = request.files["data"]
    project_name = request.form.get("project_name")
    resp = niu_app.parse(project_name, img)
    return jsonify(resp)


@flask_app.route("/train", methods=["OPTIONS", "POST"])

3 Source : admin.py
with MIT License
from ACMClassOJ

def data_upload():
    if Login_Manager.get_privilege()   <   Privilege.ADMIN:
        abort(404)
    if 'file' in request.files:
        f = request.files['file']
        try:
            r = post(DataConfig.server + '/' + DataConfig.key + '/upload.php', files={'file': (f.filename, f)})
            return {'e': 0, 'msg': r.content.decode('utf-8')}
        except RequestException:
            return ReturnCode.ERR_NETWORK_FAILURE
    return ReturnCode.ERR_BAD_DATA

3 Source : app.py
with Apache License 2.0
from adobe

def predict():
    print (request.files)
    if request.method == 'POST' and request.files['image']:
        img_list = auto.getImageList()
        img = request.files['image']
        img.save('./temp/test.png')
        img = Image.open('./temp/test.png')
        query_feature  = extract.load_sketch_query(img)
        distance  , index = auto.getSimilarImages(query_feature)
        result = []
        for i in range(1,5,1):
            result.append(str(img_list[index[0][i-1]]))
        return json.dumps(result)
    return "Image not found"

if __name__ == "__main__":

3 Source : routes.py
with MIT License
from adri711

def homework_submit():
    if request.files["homework"]:
        homework_file = request.files["homework"]
        filename = secure_filename(homework_file.filename)
        homework_file.save(os.path.join(app.config['FILE_UPLOADS'], filename))
        new_submission = AssignmentSubmission(user_id=current_user.get_id(),assignment_id=request.form['assignment_id'], file_location=filename)
        db.session.add(new_submission)
        db.session.commit()
    return jsonify({'message': 'successfuly submitted'})

@app.route('/retrieve-submissions/  <  assignment_id>', methods=['POST'])

3 Source : view.py
with Apache License 2.0
from aiorhiroki

def predict():
    img_file = request.files["image"]
    file_data = img_file.stream.read()
    nparr = np.fromstring(file_data, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    result_dir = request.files["result_dir"].stream.read()
    model_path = os.path.join(
        result_dir.decode("utf-8"), "model", "best_model.h5"
    )
    model = keras.models.load_model(model_path)
    input_img = np.expand_dims(img, axis=0) / 255
    predictions = model.predict(input_img)[0]
    predictions = [float(prediction) for prediction in predictions]
    return make_response(jsonify(dict(prediction=predictions)))


@app.route("/test", methods=["POST"])

3 Source : file.py
with MIT License
from Allen7D

def upload_file(id):
    '''上传文件'''
    files = request.files
    uploader = LocalUploader(files) # 或者导入,使用 QiniuUploader
    uploader.locate(parent_id=id)
    res = uploader.upload()
    return Success(res)


@api.route('/list', methods=['GET'])

3 Source : forms.py
with MIT License
from Allen7D

    def validate_file(self, value):
        self.file.data = request.files[value.name]


# 上传文件的校验(两个文件)
class UploadPDFValidator(BaseValidator):

3 Source : app.py
with MIT License
from AndreWohnsland

def post_file_with_mail():
    data_file = request.files["upload_file"]
    text = send_mail(data_file.filename, data_file)
    app.logger.info(text)
    return jsonify({"text": text}), 200


if __name__ == "__main__":

3 Source : api.py
with MIT License
from archivy

def image_upload():
    CONTENT_TYPES = ["image/jpeg", "image/png", "image/gif"]
    if "image" not in request.files:
        return jsonify({"error": "400"}), 400
    image = request.files["image"]
    if (
        data.valid_image_filename(image.filename)
        and image.headers["Content-Type"].strip() in CONTENT_TYPES
    ):
        saved_to = data.save_image(image)
        return jsonify({"data": {"filePath": f"/images/{saved_to}"}}), 200
    return jsonify({"error": "415"}), 415

3 Source : run_demo_server.py
with Apache License 2.0
from Ascend

def index_post():
    global predictor
    import io
    bio = io.BytesIO()
    request.files['image'].save(bio)
    img = cv2.imdecode(np.frombuffer(bio.getvalue(), dtype='uint8'), 1)
    rst = get_predictor(checkpoint_path)(img)

    save_result(img, rst)
    return render_template('index.html', session_id=rst['session_id'])


def main():

3 Source : api.py
with Apache License 2.0
from asreview

def api_import_project():
    """Import uploaded project"""

    # raise error if file not given
    if 'file' not in request.files:
        response = jsonify(message="No file found to upload.")
        return response, 400

    # set the project file
    project_file = request.files['file']
    # import the project
    project_id = import_project_file(project_file)

    # return the project info in the same format as project_info
    return jsonify(id=project_id)


@bp.route('/project/  <  project_id>/export', methods=["GET"])

3 Source : unrestricted_file_upload.py
with Apache License 2.0
from aws-samples

def file_upload_non_compliant():
    import os
    from flask import request
    upload_file = request.files['file']
    # Noncompliant: the uploaded file can have any extension.
    upload_file.save(os.path.join('/path/to/the/uploads',
                                  upload_file.filename))
# {/fact}


# {fact [email protected] defects=0}
from flask import app

3 Source : unrestricted_file_upload.py
with Apache License 2.0
from aws-samples

def file_upload_compliant():
    import os
    from flask import request
    extensions = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
    upload_file = request.files['file']
    # Compliant: the uploaded file must have one of the allowed extensions.
    if '.' in upload_file.filename and \
            upload_file.filename.split('.')[-1] in extensions:
        upload_file.save(os.path.join('/path/to/the/uploads',
                                      upload_file.filename))
# {/fact}

3 Source : main.py
with MIT License
from Azure-Samples

def classify_image():
    file = request.files['image']
    result = classifier.run_inference_on_image(file)
    return jsonify(result)


if __name__ == "__main__":

3 Source : rest_api.py
with MIT License
from Azure-Samples

    def post(self):
        input_file = request.files['img'].stream
        result = run_inference(input_file)
        return result

api.add_resource(Patient, '/patient/  <  string:patient_id>')

3 Source : files.py
with Mozilla Public License 2.0
from BoyaaDataCenter

    def post(self):
        upload_file = request.files['file']
        local_file = LocalFile()
        file_path = local_file.save(upload_file)
        if file_path:
            file_url = request.host_url + file_path.replace('\\', '/')
            return self.response_json(self.HttpErrorCode.SUCCESS, '上传成功', {'file_url': file_url})
        return self.response_json(self.HttpErrorCode.ERROR, '上传失败')

3 Source : app.py
with GNU General Public License v3.0
from christofferaakre

def upload_ebook():
    if 'file' not in request.files:
        flash('No file part')
        return redirect('/')
    file = request.files['file']

    if file.filename == '':
                flash('No selected file')
                return redirect('/')

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(save_path)
        book_data = analyse_ebook(save_path)
        file_hash = book_data['file_hash']
        return redirect(f'/books/{file_hash}')

if __name__ == '__main__':

3 Source : spk_recog_server.py
with GNU Lesser General Public License v3.0
from Ckst123

def add_data():
    username = request.files['username']
    username = username.getvalue().decode('utf-8')
    name = username
    if name not in speaker_dict.keys():
        return '등록되지 않은 화자입니다.'
    audio_file = request.files['audio_file']
    path = os.path.join(DATA_DIR, speaker_dict[name], get_time() + '.wav')
    write_wav(path, audio_file)
    train_model()
    return "Add %s's data" % name


@app.route("/delete_speaker", methods=['POST'])

3 Source : spk_recog_server.py
with GNU Lesser General Public License v3.0
from Ckst123

def speaker_recognition():
    audio_file = request.files['audio_file']
    path = os.path.join(DATA_DIR, 'test', 'test.wav')
    os.system('rm -rf %s' % path)
    write_wav(path, audio_file)
    res = test_speaker_recog()
    os.system('rm -rf %s' % path)
    return res


@app.route("/speaker_list", methods=['GET'])

3 Source : upload.py
with MIT License
from ctxis

def zones_import_upload():
    provider = Provider()
    import_manager = provider.dns_import()

    if len(request.files) != 1:
        flash('Uploaded file could not be found', 'error')
        return redirect(url_for('dns.zones_import'))

    file = request.files['csvfile']
    if file.filename == '':
        flash('No file uploaded', 'error')
        return redirect(url_for('dns.zones_import'))

    file.save(import_manager.get_user_data_path(current_user.id, filename='import.csv'))

    return redirect(url_for('dns.zones_import_review'))


@bp.route('/import/upload/review', methods=['GET'])

3 Source : form.py
with MIT License
from dhina016

        def wrap_formdata(self, form, formdata):
            if formdata is _Auto:
                if _is_submitted():
                    if request.files:
                        return CombinedMultiDict((
                            request.files, request.form
                        ))
                    elif request.form:
                        return request.form
                    elif request.get_json():
                        return ImmutableMultiDict(request.get_json())

                return None

            return formdata

        def get_translations(self, form):

3 Source : image.py
with MIT License
from DiptoChakrabarty

    def post(self):
        data = image_schema.load(request.files)
        user_id = get_jwt_identity()
        folder = f"user_{user_id}"
        try:
            image_path = image_uploader.save_images(data["image"],folder=folder)
            basename =  image_uploader.get_basename(image_path)
            return {"msg": "image uploaded {}".format(basename)},201
        except UploadNotAllowed:
            ext = image_uploader.get_extension(data["image"])
            return {"msg": "Image format incorrect"},400

class Images(Resource):

3 Source : web.py
with MIT License
from Dref360

def hello():
    img = cv2.imdecode(np.fromstring(request.files['file'].read(), np.uint8), -1)
    img = cv2.resize(img, (224, 224))
    return classes[np.argmax(keras_model.predict(img))]


if __name__ == '__main__':

3 Source : upload.py
with GNU General Public License v3.0
from eclogue

def upload_file():
    files = request.files
    form = request.form

    return jsonify({
        'message': 'ok',
        'code': 0,
    })

3 Source : cmd_exec.py
with MIT License
from fredrik-corneliusson

    def save(self):
        logger.info('Saving...')

        logger.info('field value is a file! %s', self.key)
        file = request.files[self.key]
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            raise ValueError('No selected file')
        elif file and file.filename:
            filename = secure_filename(file.filename)
            name, suffix = os.path.splitext(filename)

            fd, filename = tempfile.mkstemp(dir=self.temp_dir(), prefix=name, suffix=suffix)
            self.file_path = filename
            logger.info(f'Saving {self.key} to {filename}')
            file.save(filename)

    def __str__(self):

3 Source : app.py
with Apache License 2.0
from GoogleCloudPlatform

def post():
  form = UploadForm(CombinedMultiDict((request.files, request.form)))
  if request.method == 'POST' and form.validate():
    filename = '{}.{}'.format(
        str(uuid.uuid4()),
        secure_filename(form.input_photo.data.filename))
    content_type = content_types[filename.split('.')[-1].lower()]
    with tempfile.NamedTemporaryFile() as temp:
      form.input_photo.data.save(temp.name)
      blob = bucket.blob(filename)
      blob.upload_from_filename(temp.name, content_type=content_type)
      blob.make_public()
    db.session.add(Photo(filename))
    db.session.commit()
    publish_message('thumbnail-service', filename)
  return show_photos(form)


@app.route('/delete', methods=['POST'])

3 Source : app.py
with MIT License
from huseinzol05

def test():
    f = request.files['file']
    f.save(
        os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename))
    )
    return f.filename


@app.route('/wordcount', methods = ['POST'])

3 Source : scylla.py
with Apache License 2.0
from hyp3ri0n-ng

def progress():

    f = secure_filename(request.files['file'])
    
    f.save("/var/www/scylla/user_uploaded_dbs/" + f)
    print(f)
    
    return str("Thanks for the db!")


@app.route("/crowdsource", methods = ["GET", "POST"])

3 Source : run.py
with Apache License 2.0
from IBM

def upload_video():
    #clean
    for root, dirs, files in os.walk('clips/'):  
        for filename in files:
            os.remove('clips/' + filename)
    
    #storing video
    data = request.files['file']
    data.save("processor/" + secure_filename(data.filename))
    print("Ash - video uploaded")
    return json.dumps({'success':'true'}), 200, {'ContentType':'application/json'}

@app.route('/clips/  <  path:path>')

3 Source : views.py
with Apache License 2.0
from IBM

def upload_cert():
    if 'cert' not in request.files:
        qpylib.log('no certificate file in upload request')
        return redirect('/', code=303)
    file = request.files['cert']
    # If the user does not select a file, the browser also submits an empty part without filename
    if file.filename == '':
        qpylib.log('no certificate file in upload request')
        return redirect('/', code=303)
    filename = secure_filename(file.filename)
    file.save(os.path.join(CERTS_DIRECTORY, filename))
    refresh_certs()
    return redirect('/', code=303)


def get_certificate_management_app():

3 Source : image_controller.py
with MIT License
from iit-technology-ambit

    def post(self):
        f = request.files['file']
        img = ImgLink(f)
        return f"{ img.link }", 201


@api.route("/addLink")

3 Source : bp.py
with GNU Affero General Public License v3.0
from JHUAPL

def post_collection_image(collection_id, path):
    if not is_cached_last_collection(collection_id):
        if not get_user_permissions_by_id(collection_id).add_images:
            raise exceptions.Unauthorized()
    if "file" not in request.files:
        raise exceptions.BadRequest("Missing file form part.")

    update_cached_last_collection(collection_id)

    return jsonify(_upload_collection_image_file(collection_id, path, request.files["file"]))

def init_app(app):

3 Source : routes.py
with GNU General Public License v3.0
from jwenjian

def gif_qrcode():
    picture_file = request.files['file']
    text = request.form['text']
    temp_file_name = str(uuid.uuid4()) + '.' + picture_file.filename.split('.')[-1:][0]
    temp_file_path = os.path.join(os.getcwd(), temp_file_name)
    picture_file.save(temp_file_path)

    try:
        result_base64 = Generator.gen_gif_qrcode(text, temp_file_path)
    except Exception as e:
        return jsonify({
            "code": 1,
            "message": e
        })

    return jsonify({
        "code": 0,
        "url": result_base64
    })

3 Source : upload_controller.py
with GNU Affero General Public License v3.0
from konishi-project

    def post(self):
        """ Uploads an image for posts """
        files = request.files
        upload_folder = "postimages"
        # Add post unique extensions
        extensions = DEFAULT_EXTENSIONS + ["gif"]
        return upload_file(files, upload_folder, extensions)


@api.route("/avatar")

3 Source : upload_controller.py
with GNU Affero General Public License v3.0
from konishi-project

    def post(self):
        """ Uploads user profile picture """
        files = request.files
        upload_folder = "avatars"
        # Profile pictures will use the default extensions.
        return upload_file(files, upload_folder, DEFAULT_EXTENSIONS)

3 Source : upload_file.py
with MIT License
from maurapintor

    def post(self, data_type):
        if not os.path.isdir(DATA_FOLDER):
            os.mkdir(DATA_FOLDER)
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        # If the user does not select a file, the browser submits an
        # empty file without a filename.
        if file.filename == '':
            return redirect(request.url)
        if file and allowed_file(file.filename, data_type):
            file.save(os.path.join(DATA_FOLDER, data_type + '.' + DATA_TYPES[data_type]))
            return 200
        else:
            abort(400)

3 Source : vision_server.py
with MIT License
from Meituan-Dianping

def get_client_image():
    file = request.files['file']
    data = {
        "code": 0,
        "data": model_predict(file.read(), view=False)
    }
    return jsonify(data)


@app.errorhandler(Exception)

3 Source : image2text.py
with GNU General Public License v3.0
from mertguvencli

def img2text():
    if "image" in request.files:
        img = request.files['image']
        response = image_to_text.ImageToText(path=img).convert()
        return jsonify({"text": response}), 200
    return jsonify({"text": "Something went wrong.."}), 400

3 Source : app.py
with MIT License
from microsoft

def store_file_from_request(request, file_key, save_to_dir):
    if file_key in request.files:
        if os.path.exists(save_to_dir):
            rmtree(save_to_dir)
        os.mkdir(save_to_dir)
        temp_file = request.files[file_key]
        saved_file_path = os.path.join(save_to_dir, temp_file.filename)
        request.files[file_key].save(saved_file_path)
        return saved_file_path
    return ''


def store_files_from_request(request, file_key, save_to_dir):

3 Source : app.py
with MIT License
from microsoft

def store_files_from_request(request, file_key, save_to_dir):

    if file_key in request.files:
        if os.path.exists(save_to_dir):
            rmtree(save_to_dir)
        os.mkdir(save_to_dir)
        file_list = request.files.getlist(file_key)
        # Upload test data
        for td in file_list:
            saved_file_path = os.path.join(save_to_dir, td.filename)
            td.save(saved_file_path)


def get_convert_json(request):

3 Source : app.py
with MIT License
from mit-pdos

def photo():
    if client is None:
        return redirect(url_for("login"))

    if "photo" not in request.files:
        abort(400)

    data = request.files["photo"].read()
    if len(data) == 0:
        abort(400)

    if client.put_photo(data) is None:
        abort(500)

    return _list_photos()

@app.route("/photo/  <  num>", methods=["GET"])

3 Source : validator.py
with MIT License
from nazarimilad

    def validate(request):
        # check if the post request has the file part
        if "file" not in request.files:
            flash("No file part")
            raise ValueError("No file selected")
        file = request.files["file"]
        # if user does not select file, browser also
        # submit an empty part without filename
        if not file or file.filename == "":
            flash("No selected file")
            raise ValueError("File name is not valid")
        if not Validator._is_file_extension_allowed(file.filename):
            flash("Invalid extension")
            raise ValueError("File name is not valid")
        filename = secure_filename(file.filename)
        return file, filename

3 Source : onnx_registry.py
with MIT License
from neurom-iot

def upload_process():
    f = request.files['file']
    print(f)
    file_name = f.filename
    file_path = os.getcwd() + '\\' + onnx_folder_path[:-1] + '\\'  # 파일 저장 위치 경로
    f.save(file_path + file_name)  # 저장할 경로 + 파일명
    print(file_path + file_name + '에 파일 저장 완료')

    user_ip = request.remote_addr
    upload_time = time.strftime('%y-%m-%d %H:%M:%S')

    # txt 파일 저장
    f = open(log_file_path + "log.txt", 'a+')
    f.write(
        '(' + upload_time + ') - ' + 'Upload_Success     ' + ' - ' + file_name + ' - ' + user_ip + ' - ' + file_path + '\n')
    f.close()
    return redirect('/')

@app.route('/post', methods=['POST'])

3 Source : app.py
with Apache License 2.0
from nginyc

def create_model(auth):
    admin = get_admin()
    params = get_request_params()

    # Expect model file as bytes
    model_file_bytes = request.files['model_file_bytes'].read()
    params['model_file_bytes'] = model_file_bytes

    # Expect model dependencies as dict
    if 'dependencies' in params and isinstance(params['dependencies'], str):
        params['dependencies'] = json.loads(params['dependencies'])

    with admin:
        return jsonify(admin.create_model(auth['user_id'], **params))

@app.route('/models/available', methods=['GET'])

3 Source : web_app.py
with Apache License 2.0
from oke-aditya

def simfeat():
    r = request.files["image"]
    # print("Hi")
    # convert string of image data to uint8
    nparr = np.fromstring(r.data, np.uint8)
    # decode image
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    indices_list = compute_similar_features(img, num_images=5, embedding=embedding)
    # Need to display the images
    return (
        json.dumps({"indices_list": indices_list}),
        200,
        {"ContentType": "application/json"},
    )


@app.route("/simimages", methods=["POST"])

3 Source : web_app.py
with Apache License 2.0
from oke-aditya

def simimages():
    image = request.files["image"]
    # print("Hi")
    image = Image.open(image)
    image_tensor = T.ToTensor()(image)
    image_tensor = image_tensor.unsqueeze(0)
    indices_list = compute_similar_images(
        image_tensor, num_images=5, embedding=embedding, device=device
    )
    # Need to display the images
    return (
        json.dumps({"indices_list": indices_list}),
        200,
        {"ContentType": "application/json"},
    )


if __name__ == "__main__":

3 Source : script.py
with MIT License
from p-rit

def upload_file():
			content = request.files['file']
			style = request.form.get('style')
			content.save(os.path.join(app.config['UPLOAD_FOLDER'], 'content.jpg'))
			#load in content and style image
			content = load_image('./static/image/upload'+content.filename)
		 	#Resize style to match content, makes code easier
			style = load_image('./static/image/'+ style+'.jpg', shape=content.shape[-2:])
			vgg = model()
			target = stylize(content,style,vgg)
			x = im_convert(target)
			plt.imsave(app.config['UPLOAD_FOLDER']+'target.png',x)

			return render_template('success.html')

							

if __name__ =="__main__":

See More Examples