与请求一起发送到其他API时,上传到Flask的文件为空

时间:2019-06-12 14:54:58

标签: python flask python-requests werkzeug

我在Flask中有一个API,该API可以接收上传的文件,并根据请求将其上传到另一个API。但是,无法通过请求上传文件,第三方API会返回错误No files provided

@deals_bp.route('/file', methods=['POST'])
def upload_deal_file():
    args = request.args.to_dict()
    args['api_token'] = os.environ.get('API_TOKEN')

    if request.method == 'POST':
        data_err_str = ''
        data = request.form.to_dict()

        if not data['deal_id']:
            data_err_str = 'deal_id not included'
        elif not set(data.keys()).issubset(['deal_id']):
            data_err_str = 'no data other than deal_id must be included'

        if 'file' not in request.files:
            return abort(400, description="Please select a pdf file " + data_err_str)

        # definition of the file variable, a Werkzeug FileStorage object
        file = request.files['file']

        if file.filename == '':
            return abort(400, description="Please select a pdf file " + data_err_str)

        if file and allowed_file(file.filename):
            if data_err_str != '':
                return abort(400, description=data_err_str)

            # beginning of problem code block
            file_obj = {'file': (file.filename, file.read())}
            response = requests.post(os.environ.get('API_URL') + '/files', params=args, files=file_obj, data=data)
            # end of problem code block

            res_gzip = gzip.compress(response.content)
            return (res_gzip, response.status_code, response.headers.items())
        else:
            return abort(400, description="File is not pdf" + data_err_str)

response中的requests.post是:

{
    "success": false,
    "error": "No files provided",
    "error_info": "Please check developers.pipedrive.com for more information about Pipedrive API.",
    "data": null,
    "additional_data": null
}

0 个答案:

没有答案