【问题标题】:Python KeyError | API ResponsePython KeyError | API 响应
【发布时间】:2017-07-19 17:26:46
【问题描述】:

我为我正在使用的 API 创建了一个包装器。完整的包装在这里:https://pastebin.com/nL089zwF

我正在使用以下代码进行通话:

balanceBTC = api.GetBalance('BTC')
for i in balanceBTC['data']:
    if i['symbol'] == 'btc':
        print i['available']

响应如下:

AttributeError: 'dict' object has no attribute 'respond'

Trace 将代码的第 50 行标识为问题:

return response.respond["false","False"].respond["true","True"].respond['":null','":None' ]

所以我删除了 .respond 并留下了一个新错误:

return response["false","False"], ["true","True"], ['":null','":None' ]
KeyError: ('false', 'False')

我知道响应是一个字典,它没有密钥,这就是导致错误的原因(我认为?)但我是一个初学者,我正在学习,我不知道要更改/添加/删除什么代码本身。

如果您能提供指导,我将不胜感激!谢谢。

以下是负责获取响应的 API 包装器的完整部分:

def api_query(self, method, values, req = None ):
            if not req:
                req = {}
            #print "def api_query( method = " + method + ", req = " + str( req ) + " ):"
            time.sleep(1)
            if method in self.public:
                url = 'https://www.cryptopia.co.nz/api/'
            elif method in self.private:
                url = 'https://www.cryptopia.co.nz/api/'
            else:
                return 'Call Not Identified - Something Went Wrong.'

            url += method + '?' + urllib.urlencode(values)

            if method not in self.public:
                url = "https://www.cryptopia.co.nz/Api/" + method
                nonce = str( int( time.time() ) )
                post_data = json.dumps( req );
                m = hashlib.md5()
                m.update(post_data)
                requestContentBase64String = base64.b64encode(m.digest())
                signature = self.key + "POST" + urllib.quote_plus( url ).lower() + nonce + requestContentBase64String
                hmacsignature = base64.b64encode(hmac.new(base64.b64decode( self.secret ), signature, hashlib.sha256).digest())
                header_value = "amx " + self.key + ":" + hmacsignature + ":" + nonce
                headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
                r = requests.post( url, data = post_data, headers = headers )
            response = json.loads(r.text)

            return response.respond["false","False"].respond["true","True"].respond['":null','":None' ]

【问题讨论】:

  • 似乎 api 需要密钥和秘密,所以我们可能无法重现该错误。但是您可以确认响应类型是什么——print type(response) 显示什么?取决于您使用的响应定义。 response = r.text 应该显示<type 'str'>,而response = json.loads(r.text),然后type(response) 应该显示<type 'dict'>
  • 它确实需要它们,我将它们输入到一个名为 secrets.json 的文件中。它从该文件中提取密钥和秘密。我之前使用过 response = r.text,它给了我错误 TypeError: string indices must be integers 所以我将它切换到 response = json.loads(r.text) 并得到 KeyError ...对不起,如果这不清楚.任何的想法? @downshift
  • json.loads(r) 仅在 r 是字典、<type 'dict'>r.text 应该是 type(r.text) -> <type 'unicode'> 时才有效。您希望该方法返回什么内容或type 的内容?回复的文字?一个布尔值,例如True/False?
  • 文本响应,它是一个最多 8 位小数的数字,即 1.12345678
  • response.text 包含数字?它可能是一个表示为 'unicode' 字符串的数字 - type(r.text) 输出什么?这个数字是你要在函数调用中返回的?

标签: python json api response keyerror


【解决方案1】:

后期编辑: 错误已解决,它得到了错误的密钥('data',而不是 'Data')

无论如何,正确的版本在这里(使用的那个)。

def api_query(self, method, values, req = None ):
if not req:
    req = {}
time.sleep(1)
if method in self.public:
    url = 'https://www.cryptopia.co.nz/api/'
elif method in self.private:
     url = 'https://www.cryptopia.co.nz/api/'
else:
    return 'Call Not Identified - Something Went Wrong.'
url += method + '?' + urllib.urlencode(values)
if method not in self.public:
    url = "https://www.cryptopia.co.nz/Api/" + method
    nonce = str( int( time.time() ) )
    post_data = json.dumps( req );
    m = hashlib.md5()
    m.update(post_data)
    requestContentBase64String = base64.b64encode(m.digest())
    signature = self.key + "POST" + urllib.quote_plus( url ).lower() + nonce + requestContentBase64String
    hmacsignature = base64.b64encode(hmac.new(base64.b64decode( self.secret ), signature, hashlib.sha256).digest())
    header_value = "amx " + self.key + ":" + hmacsignature + ":" + nonce
   headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
    r = requests.post( url, data = post_data, headers = headers )
return r.json() #changed here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2017-03-04
    • 2021-09-01
    相关资源
    最近更新 更多