如何将标头中的字典作为值发送到Python请求中的“授权”键?

问题描述 投票:0回答:2

我必须测试API的结果。我正在发送

Key - 'Authorization'
value - { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}

我在邮递员中得到正确的输出,但我的代码在请求中失败

import requests
from pprint import pprint

def main():
    url = "http://test.example.com/recharger-api/merchant/getPlanList?circleid=1&operatorid=1&categoryid=1"
    headers = {'Authorization': { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}}
    response = requests.get(url, headers = headers)
    data = response.json()
    pprint(data)

if __name__ == "__main__":
    main()

我得到的错误:

requests.exceptions.InvalidHeader: Value for header {'Authorization': { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}} must be of type str or bytes, not <class 'dict'>
python python-3.x python-requests
2个回答
5
投票

标头几乎肯定需要 JSON 数据。 Python 字典,即使简单地转换为字符串,也与 JSON 不同。无论如何,

requests
库不接受除标题字符串之外的任何内容。 POSTMan 仅处理字符串,而不处理 Python 对象,因此您不会在那里看到问题。

显式转换它:

import json

headers = {
    'Authorization': json.dumps({
        "merchantIp": "13.130.189.149",
        "merchantHash": "c8b71ea1ab250adfc67f90938750cd30",
        "merchantName": "test"
    })
}

-1
投票

Martijn Pieters,非常感谢您的评论。我在代码中遇到了同样的问题,但不理解这个问题/Python Dicts X JSON Strings 的差异...在我的代码中,我有两个 JSON 部分,“headers”和“body”,所以我不得不“json.dumps” “字典的正文部分

© www.soinside.com 2019 - 2024. All rights reserved.