Python 请求不起作用,但 cURL 可以对 PUT 文件起作用

问题描述 投票:0回答:1

我在使用 python 的请求库发出 api 请求时遇到问题。

我已经使用 cURL 测试了端点并且它可以工作,但是我的 python 代码中的某些内容使 api 调用失败,状态为 500。我的猜测是这与数据/文件的结构有关。 有人看到我看不到的明显错误吗?

我首先尝试使用 Postman,它有效,并且它输出的 cURL 命令也有效。

curl --location --request PUT 'https://myurl/endpoint' 
--header 'client-id: my-client-id' 
--header 'client-secret: my-client-secret' 
--header 'correlation-id: my-correlation-id' 
--header 'backend: service' 
--form 'entity_content={"Title":"1megabytetestimage","PathOnClient":"1mbimage.jpg"};type=application/json' 
--form 'VersionData=@"/path/to/1mbimage.jpg"' 
--cert certificate.pem

不起作用的Python代码是:

import requests

url = 'https://myurl/endpoint'
headers = {
    'client-id': 'my-client-id',
    'client-secret': 'my-client-secret',
    'correlation-id': 'my-correlation-id',
    'backend': 'service',
}

data = {
    'entity_content': '{"Title":"1megabytetestimage","PathOnClient":"1mbimage.jpg"};type=application/json'
}


files = {
    'VersionData': ('1mbimage.jpg', open('/mnt/d/1mbimage.jpg', 'rb'), 'image/jpeg'),
}

response = requests.put(url, headers=headers, files=files, data=data, cert='certificate.pem')

我已经尝试了大量的迭代,但到处都有微小的变化,但似乎没有任何效果。 不幸的是我无法提供实际的 url、客户端 ID 和秘密。

python python-3.x curl python-requests
1个回答
0
投票

尝试在

requests.put()
调用中使用 json 参数而不是数据。

import requests
import json

url = 'https://myurl/endpoint'
headers = {
    'client-id': 'my-client-id',
    'client-secret': 'my-client-secret',
    'correlation-id': 'my-correlation-id',
    'backend': 'service',
}

data = {
    'Title': '1megabytetestimage',
    'PathOnClient': '1mbimage.jpg'
}

files = {
    'VersionData': ('1mbimage.jpg', open('/mnt/d/1mbimage.jpg', 'rb'), 'image/jpeg'),
}

response = requests.put(url, headers=headers, files=files, json=data, cert='certificate.pem')
© www.soinside.com 2019 - 2024. All rights reserved.