简体   繁体   English

Python发送POST请求/multipart/form-data

[英]Python sending POST requests/ multipart/form-data

I'm just working on API conection at my work.我只是在工作中处理 API 连接。 I already made some GET and PUT request, but now i have problem with POST.我已经提出了一些 GET 和 PUT 请求,但现在我有 POST 问题。 API documantation is here . API 文档在这里 And here is my code I test but get 400 bad request:这是我测试的代码,但收到 400 个错误的请求:

import requests

files = {'files': ('fv.pdf', open(r"C:\python\API\fv.pdf", 'rb'))}
data = {"order_documents":[{'file_name':"fv.pdf", 'type_code':'CUSTOMER_INVOICE' }]}

header = {
    'Authorization': '###########################',
}
response = requests.post("https://######.com/api/orders/40100476277994-A/documents", headers=header, files = files, data = data)

print(response.status_code)
print(response.url)

Someone have any idea how i can handle with this?有人知道我该如何处理吗?

Looks like you are missing the order_documents parameter, it needs to be an array and also needs to be called order_documents.看起来您缺少order_documents参数,它需要是一个数组,还需要称为 order_documents。

Try changing your data variable into:尝试将您的data变量更改为:

data = {"order_documents": [ {'file_name':"fv.pdf", 'type_code':'CUSTOMER_INVOICE' } ] }

The API expects files as the parameter name and your dictionary sends file to the server. API 需要files作为参数名称,您的字典将file发送到服务器。 The parameter name files that you give to session.post is just for requests library and not the actual parameter sent to the server.您提供给session.post的参数名称files仅用于requests库,而不是发送到服务器的实际参数。 The API also expects multiple files in an array, so you need to change your files object. API 还需要一个数组中的多个文件,因此您需要更改文件对象。

files = [
    ('files', ('fv.pdf', open(r"C:\python\API\fv.pdf", 'rb')),
]

Also, I don't think you need to use requests.Session(), just use requests.post(), unless you're planning on using the session object multiple times for subsequent requests.另外,我认为您不需要使用 requests.Session(),只需使用 requests.post(),除非您计划为后续请求多次使用会话对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM