繁体   English   中英

如何使用请求在 Python 中发布多部分/表单数据

[英]How to POST multipart/form-data in Python with requests

目前正在做一个项目,我需要发布这个请求:

curl -X POST "http://localhost:8000/api/v1/recognition/recognize" \
-H "Content-Type: multipart/form-data" \
-H "x-api-key: xxxxxx-xxxxx-xxxx-xxxx-xxxxxxxx" \
-F "file=@<image>.jpg"  #image

用这个代码片段尝试了几次都没有运气:

import requests
headers = {
    'Content-Type': 'multipart/form-data',
    'x-api-key': 'xxxxxxxxxxxx',
}
files = {
    'file': ('image.jpg', open('image.jpg', 'rb')),
}
response = requests.post('http://localhost:8000/api/v1/recognition/recognize', headers=headers, files=files)
print(response)

我做错了什么或遗漏了什么?

试试这个

import requests

headers = {
    'Content-Type': 'multipart/form-data',
    'x-api-key': 'xxxxxx-xxxxx-xxxx-xxxx-xxxxxxxx',
}

files = {
    'file': ('<image>.jpg', open('<image>.jpg', 'rb')),
}

response = requests.post('http://localhost:8000/api/v1/recognition/recognize', headers=headers, files=files)

-H标志意味着您正在传递标头,而不是文件。

>>> import requests
>>> 
>>> headers = {
...     "Content-Type": "multipart/form-data",
...     "x-api-key": "xxxxxx-xxxxx-xxxx-xxxx-xxxxxxxx"
... }
>>> 
>>> file = {"file": ("<image>.jpg", open("<image>.jpg", "rb"))}
>>> 
>>> r = requests.post("http://localhost:8000/api/v1/recognition/recognize",
...     headers=headers, files=file
... )

我用这个代码让它工作:

import requests
url = "http://10.0.38.119:8000/api/v1/recognition/recognize"
payload = {}
files = [('file', ('<image>.jpg', open('<image>.jpg', 'rb'), 'image/jpeg'))]
headers = {
  'x-api-key': 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)

暂无
暂无

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

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