File uploaded to Flask is empty when sending to other API with requests

Viewed 465

I have an API in Flask that takes an uploaded file and uploads it to another API with requests. However, uploading the file with requests doesn't work, the 3rd party API comes back with the error 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)

The response from requests.post is:

{
    "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 Answers
Related