【问题标题】:Python Post - keep getting response 400, but curl worksPython Post - 不断收到响应 400,但 curl 有效
【发布时间】:2017-07-28 16:12:21
【问题描述】:

我有一个简单的 python 3 脚本,它发送一个发布请求以删除 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 命令可以正常工作:

curl -X POST -H "Authorization: Basic YWRtaW46YWRtaW4=" -F "key=com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view" "http://devsonar/api/projects/delete"

【问题讨论】:

    标签: python curl sonarqube python-requests


    【解决方案1】:

    Python requests 确实是一个很好的库。帖子中的文件选项用于上传文件,我认为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 中使用 requests 库上传文件的详细信息。

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

    import requests
    headers = {'Authorization': 'Basic YWRtaW46YWRtaW4='}
    data = {'key': 'com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view'}
    response=requests.post(url,data=data,headers=headers)
    

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

    【讨论】:

      【解决方案2】:

      您应该使用数据而不是文件作为 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)
      

      【讨论】:

        猜你喜欢
        • 2016-01-09
        • 2020-10-27
        • 2021-06-08
        • 1970-01-01
        • 2020-07-21
        • 2016-07-28
        • 2016-11-23
        • 1970-01-01
        • 2021-07-10
        相关资源
        最近更新 更多