3

So I built an API which takes in a pdf file and json and converts the file into text. Testing with Postman works fine, however now I try to make a script to send multiple images and the API does not receive the image I send it in the script. It receives the request but not its contents. Additionally I don't get the json file either, while it does show on the script side.

I looked at the Postman request and implemented it in the script, however it still does not work. I tried sending only the file without a json and could not get it working. I've been looking in the documentation of flask and request, but I'm not able to find the explanation why it does not receive the image.

#Script code
import requests
import time
import glob

url = "http://127.0.0.1:5000/transcribe"
for file in glob.glob("/Receipts_to_scan/*.pdf"):

    print(open(file, "rb"))

    files = {
        'file': open(file, 'rb'),
        'json': '{"method":"sypht"}'
    }

    headers = {
        'Accept': "application/pdf",
        'content-type': "multipart/form-data",
        'Connection': 'keep-alive'
    }

    response_decoded_json = requests.post(url, files=files, headers=headers)
    time.sleep(5)
    print(response_decoded_json)

#--------------------------
#API code
from flask import Flask, request
@app.route("/transcribe", methods = ["POST"])
def post():
    #Getting the JSON data with all the settings in it
    json_data = request.files["json"]
    print(json_data)
    image = request.files["file"]
    print(image)

1 Answer 1

4

Could you try the following? This way you can combine a file and other data (like a dictionary) in a request.

Change your Flask API:

#Getting the JSON data with all the settings in it
json_data = request.form    # <--- change this line
print(json_data)

And then make a request like this (without manually setting the headers):

files = {
    'file': (file, open(file, 'rb'), "application/pdf")
}

data = {
    "method": "sypht"
}

response_decoded_json = requests.post(url, files=files, data=data)
time.sleep(5)
print(response_decoded_json)

This should give you an ImmutableMultiDict and a FileStorage object to work with.

Your API then prints:

ImmutableMultiDict([('method', 'sypht')])

<FileStorage: 'test.pdf' ('application/pdf')>
Sign up to request clarification or add additional context in comments.

2 Comments

Nice! This helped! The only change I made to get it working was to specify the file type in the files variable.
do you mind sharing the code for your changes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.