因此,我构建了一个API,它接受pdf文件和json,并将文件转换为文本。使用Postman测试可以很好地工作,但是现在我尝试创建一个脚本来发送多个图像,但API无法接收到我在脚本中发送的图像。它接收请求,但不接收其内容。另外,我也没有得到json文件,而它确实显示在脚本端。
我查看了Postman请求并在脚本中实现了它,但是它仍然不起作用。我尝试只发送没有json的文件,但无法使其正常工作。我一直在查找flask和request的文档,但我找不到为什么它没有收到图像的原因。
#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)发布于 2019-08-08 19:41:25
你可以试试下面的方法吗?通过这种方式,您可以在请求中组合文件和其他数据(如字典)。
更改Flask API:
#Getting the JSON data with all the settings in it
json_data = request.form # <--- change this line
print(json_data)然后发出如下请求(无需手动设置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)这将为您提供一个ImmutableMultiDict和一个FileStorage对象来使用。
然后,您的API将打印:
ImmutableMultiDict([('method', 'sypht')])
<FileStorage: 'test.pdf' ('application/pdf')>https://stackoverflow.com/questions/57409431
复制相似问题