Post 使用 python 请求上传多个文件的多部分表单

Post multipart form with multiple file uploads using python requests

我以 python 字典列表的形式为某些人提取了人口统计信息(每个字典对应一个人)。我还需要从提取数据的位置上传文档 (pdf/word)。我尝试使用 Python 请求提交多部分表单,但由于某些原因似乎不起作用。

API 需要两个键 'files' 和 'data' 'files' 是文件对象列表 'data' 是使用 json.dumps(API 要求)

进行字符串化的字典列表
pay_part= [{"umr":"","age":"","gender":"","first_name":"","middle_name":"","last_name":"","phone":"","address":"","admission_date":"","lab":"","discharge_date":"","ip_number":"","diagnosis":"","reason":"","treatment":"","medications":"","expired_date":"","instructions":"","review_date":"","procedure":"","notes":"","physician":"","filename":""},{"umr":"","age":"","gender":"","first_name":"","middle_name":"","last_name":"","phone":"","address":"","admission_date":"","lab":"","discharge_date":"","ip_number":"","diagnosis":"","reason":"","treatment":"","medications":"","expired_date":"","instructions":"","review_date":"","procedure":"","notes":"","physician":"","filename":""}]

multipart_data = MultipartEncoder(
fields={
        "file":[('file.docx',open('13427.docx', 'rb'),'text/plain'), 
        ('file.docx',open('13427.docx', 'rb'),'text/plain')],
         "payload": json.dumps(pay_part)
        }
                                  )

response = requests.post(url, data=multipart_data, headers={'Content-Type': 'multipart_data.content_type; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW', 'userid': sUserID,'metaid': metaid,'postman-token':postmanToken})
print(response.text)

在形成多部分表单对象时出现错误 "AttributeError: 'tuple' object has no attribute 'encode'".

我相信这与将文件对象创建为二进制文件对象并存储在列表中有关。

提前致谢!

我成功了!

只需使用参数“数据”发送您的 json object 并使用参数“文件”发送您的文件列表 object,如下所示。

我从 header 参数中删除了“'Content-Type': 'multipart_data.content_type; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW'”

post 请求是作为一个多部分发出的 post

代码:-

fields={'payload': json.dumps(pay_part)})

response = requests.post(url, data=fields,files =[('file',open('13385.docx', 'rb')),('file',open('13385.docx', 'rb'))],  headers={'userid': sUserID,'metaid': metaid,'postman-token':postmanToken})
print(response.text)