所以我构建了一个 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)
最佳答案
您可以尝试以下操作吗?这样您就可以在请求中组合文件和其他数据(例如字典)。
更改您的 Flask API:
#Getting the JSON data with all the settings in it
json_data = request.form # <--- change this line
print(json_data)
然后发出这样的请求(无需手动设置 header ):
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')>
关于python - API、Python、请求未收到 POST pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57409431/