gpt4 book ai didi

python - REST API POST 请求导致 AttributeError : 'bytes' object has no attribute 'items'

转载 作者:太空宇宙 更新时间:2023-11-03 14:12:54 24 4
gpt4 key购买 nike

我正在尝试向 Python 3 中的 Coinigy API 发出 POST 请求。这是我一直在运行的代码。

from urllib.request import Request, urlopen
from urllib.parse import urlencode

headers = {
'Content-Type':'application/json',
'X-API-KEY':'mykey',
'X-API-SECRET':'mysecretkey'
}

values = {
"exchange_code": "BINA",
"exchange_market": "BTC/USDT",
"type": "all"
}


values = urlencode(values).encode("utf-8")
headers = urlencode(headers).encode("utf-8")


request = Request('https://api.coinigy.com/api/v1/data', data=values, headers=headers)
response_body = urlopen(request,values).read()
print(response_body)

我收到以下错误:

 AttributeError                            Traceback (most recent call last)
<ipython-input-41-504342401726> in <module>()
19
20
---> 21 request = Request('https://api.coinigy.com/api/v1/data',
data=values, headers=headers)
22 response_body = urlopen(request,values).read()
23 print(response_body)

~/anaconda3/lib/python3.6/urllib/request.py in __init__(self, url,
data, headers, origin_req_host, unverifiable, method)
333 self.data = data
334 self._tunnel_host = None
--> 335 for key, value in headers.items():
336 self.add_header(key, value)
337 if origin_req_host is None:

AttributeError: 'bytes' object has no attribute 'items'

通过过去的 POST 请求,我向他们的 API 写入了用于拉取帐户事件信息的信息,我发现我需要使用 urlencode(headers).encode("utf-8") 来获取正确的格式以通过API。但现在看来这不起作用了。 https://coinigy.docs.apiary.io/#reference/account-data/activity-log/activity

如果我注释掉编码为 utf-8 行的 header ,它似乎可以到达 Coinigy,但随后它会返回以下错误代码:

 b'{"err_num":"1057-14-01","err_msg":"Missing or empty parameters:"}'

但是 urllib.request 说你必须将 header 作为字典 {} 传递,所以我无法理解出了什么问题,它应该是正确的数据结构。

最佳答案

您不应该对您的 header 进行URL编码。 Request expects headers to be a dictionary :

headers should be a dictionary, and will be treated as if add_header() was called with each key and value as arguments.

这些是 HTTP header ,通过网络发送时采用以下形式(换行符分隔, header 名称和值之间用冒号空格):

User-Agent: Mozilla/5.0 blah blah
Content-Length: 500

因此,您应该传递 headers 字典,而不对其执行 urlencode 操作。

这个 github 存储库也可能对您有帮助:https://github.com/coinigy/api/blob/master/coinigy_api_rest.py

关于python - REST API POST 请求导致 AttributeError : 'bytes' object has no attribute 'items' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48374582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com