【问题标题】:How to send API key in the header of python request?如何在 python 请求的标头中发送 API 密钥?
【发布时间】:2021-03-21 10:51:23
【问题描述】:

我正在尝试使用文件作为输入和一些令牌发出 http post 请求,我在请求标头中传递了这些令牌,这在邮递员那里工作正常,但同样不能通过 python 代码工作 下面是我的代码正在尝试但收到 401 错误

files = {'upload_file': open('small.csv', 'rb')}
url = 'https://www.test.com'
header = {'token', 'abcd'}
r = requests.post(url, headers=header, files=files)

【问题讨论】:

    标签: python python-3.x python-2.7 python-requests postman


    【解决方案1】:

    试试这个。请求中缺少一些内容,例如类型。

    import requests
    
    try:
        url = 'https://httpbin.org/post'
        files = {'file': ('report.csv')}
    
        payload={}
        files=[
        ('file',('report.csv',open('/report.csv','rb'),'text/csv'))
        ]
        headers = {
        'Accept': 'application/json',
        'Authorization': 'Bearer 0000000'
        }
    
        response = requests.request("POST", url, headers=headers, data=payload, files=files)
    
    
    except Exception as err:
        print(err)
    

    【讨论】:

      【解决方案2】:

      您的标题字典语法不正确:

      改变:

       header = {'token', 'abcd'}
      

      收件人:

      header = {'token': 'abcd'}
      

      字典是有序的(来自 Python 3.6+)键值集合

      您可以通过postman生成任何语言绑定的等价代码,只需点击url下的代码链接并选择语言即可。它显示了正确的 python 语法:

      【讨论】:

        猜你喜欢
        • 2018-01-21
        • 1970-01-01
        • 1970-01-01
        • 2019-05-02
        • 1970-01-01
        • 2013-10-24
        • 2016-03-25
        • 1970-01-01
        • 2020-08-12
        相关资源
        最近更新 更多