Python Post一直得到400的响应,但是curl起作用了

2024-10-01 09:26:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的python3脚本,它发送post请求以删除SonarQube中的项目。当我继续使用python脚本时,一个简单的curl命令可以工作。。。你知道我的python脚本有什么问题吗?在

import requests

headers = {
    'Authorization': 'Basic YWRtaW46YWRtaW4=',
}

files = [
    ('key', 'com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view'),
]

r = requests.post('http://devsonar/api/projects/delete', headers=headers, files=files)
print(r)

以下curl命令可以正常工作:

^{pr2}$

Tags: 项目import命令脚本basicfilescurlpost
2条回答

Python请求确实是一个很好的库。post中的Files选项用于上载文件,我不认为com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view是一个文件,如果是这样,您必须以二进制模式读取该文件,然后像files = {'key': open(filename, 'rb')}一样发送它。所以代码应该是:

import requests
files = {'key': open(filename, 'rb')}
headers = {'Authorization': 'Basic YWRtaW46YWRtaW4='}
response=requests.post(url,files=files)

check this有关使用python中的请求库上载文件的详细信息。在

如果不是一个文件,您可以像这样将有效负载作为字典直接发送:

^{pr2}$

check this有关发送有效负载的详细信息。在

您应该使用数据而不是文件作为python脚本的输入,这应该可以:

import requests

headers = {
    'Authorization': 'Basic YWRtaW46YWRtaW4=',
}

files = [
    ('key', 'com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view'),
]

r = requests.post('http://devsonar/api/projects/delete', headers=headers, data=files)

相关问题 更多 >