TypeError:没有字符串参数的编码

时间:2017-07-13 15:58:02

标签: python

我查了很多类似的问题,但遗憾的是,没有一个问题与我的相近。

我有一个简单的脚本来检查来自交换的余额。它是用python编写的非官方API包装器的一部分,我的理解是它介于python 2和python 3之间。我一个接一个地修复错误,但我完全坚持这个。这是代码:

import urllib.parse
import urllib.request
import json
import time
import hmac,hashlib


class Poloniex():
    def __init__(self, APIKey, Secret):
        self.APIKey = APIKey
        self.Secret = Secret

    def api_query(self, command, req={}):
        self.req = bytes(req, 'utf-8')
        req['command'] = command
        req['nonce'] = int(time.time()*1000)
        post_data = urllib.parse.quote(req)
        my_key = self.Secret
        my_key_bytes = bytes(my_key, 'utf-8')
        post_data_bytes = bytes(post_data, 'utf-8')

        sign = hmac.new(my_key_bytes, post_data_bytes, hashlib.sha512).hexdigest()
        headers = {
        'Sign': sign,
        'Key': my_key_bytes,
        #'Content-Type': 'application/json'
        }

        ret = urllib.request.urlopen(
            urllib.parse.quote('https://poloniex.com/tradingApi', safe=':/'), post_data_bytes,
                headers)
        jsonRet = json.loads(ret.read())
        return self.post_process(jsonRet)

    def returnBalances(self):
        return self.api_query('returnBalances')



inst = Poloniex("AAA-BBB", "123abcdef")

balance = inst.returnBalances()
print(balance)

看起来我的语法有问题,但即使在RTM之后,我也无法解决这个问题。它抛出了我:

TypeError: encoding without a string argument

之前我曾:

TypeError: quote_from_bytes() expected bytes

已修复'由

self.req = bytes(req, 'utf-8')

有人可以指出我正确的方向吗?

谢谢。

UPD

抱歉,忘记了追溯

Traceback (most recent call last):
  File "script.py", line 43, in <module>
    balance = inst.returnBalances()
  File "script.py", line 37, in returnBalances
    return self.api_query('returnBalances')
  File "script.py", line 18, in api_query
    post_data = urllib.parse.quote(req)
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/parse.py", line 775, in quote
    return quote_from_bytes(string, safe)
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/parse.py", line 800, in quote_from_bytes
    raise TypeError("quote_from_bytes() expected bytes")
TypeError: quote_from_bytes() expected bytes

1 个答案:

答案 0 :(得分:2)

在您的代码中,req是一个字典,但是您尝试将其转换为bytes此处:self.req = bytes(req, 'utf-8'),这没有意义,因为只能转换字符串这样。

第二个错误是由于urllib.parse.quote仅适用于字符串和bytes,但您传递的是字典。