如何在 python 请求的 header 中发送 API 键?

How to send API key in the header of python request?

我正在尝试使用文件作为输入和我在请求 header 中传递的一些令牌发出 http post 请求,这在 postman 中运行良好但通过 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)

您 header 的词典语法不正确:

更改:

 header = {'token', 'abcd'}

收件人:

header = {'token': 'abcd'}

字典排序key-valuecollectionPython3.6+

您可以通过邮递员生成任何语言绑定的相等代码,只需单击 url 和 select 语言下的代码 link 即可。它显示了正确的 python 语法:

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

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)