【问题标题】:python equivalent of curl command which has api token basic auth [duplicate]具有api令牌基本身份验证的curl命令的python等效项[重复]
【发布时间】:2019-10-31 14:16:11
【问题描述】:

我正在研究 helpshift api,并试图找到一个准确的请求调用,该调用将返回问题元数据。我尝试了很多例子,但它总是返回 401 状态。

但是我能够让 curl 命令工作

提供给我的东西是:apikey,url,return是json响应

有效的 CURL 命令是:

curl -X GET --header 'Accept: application/json' --header 'Authorization: Basic <base64_encoded_version_of_api_key_for_basic_auth>' '<helpshift_url>'

我尝试过的事情如下:

>>> api_key = "ABCDEFGH"
>>> issue = '<helpshift_url>'
>>> 
>>> r = requests.get( issue, auth = ( api,"" ))
>>> r.status_code
401
>>> 
>>> import base64
>>> api_new = base64.b64encode(api_key.encode("UTF-8"))
>>> 
>>> r = requests.get( issue, auth = ( api_new,"" ))
>>> r.status_code
401

我想要得到的是打印的 json 响应

【问题讨论】:

    标签: python http curl python-requests


    【解决方案1】:

    您需要使用标题:

    >>> import base64
    >>> api_new = base64.b64encode(api_key.encode("UTF-8"))
    >>> 
    >>> r = requests.get( issue, header="Authorization: Basic {}'.format(api_new))
    

    【讨论】:

      【解决方案2】:

      requests auth param 负责 http 基本认证。从我在您的代码中看到的内容来看,您想要修改标头而不是执行身份验证。

      这是通过将标头字典 headers = {'Authorization': api_new} 作为 r = requests.get( issue, headers=headers) 传递给请求来完成的。

      完整的代码

      import base64
      import requests
      
      api_key = "ABCDEFGH"
      issue = '<helpshift_url>'
      
      api_new = base64.b64encode(api_key.encode("UTF-8"))
      headers = {'Authorization': api_new}
      
      r = requests.get( issue, headers=headers)
      
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-27
        • 2021-01-25
        • 2017-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多