TypeError:__repr__返回非字符串(类型字节)

时间:2015-06-03 16:35:04

标签: python python-3.x oauth ipython discogs-api

我正在尝试使用Discogs API访问Python client library

以下是我尝试与Discogs API进行交互的最小示例:

from SensitiveInformation.discogs_application_info import provide_discogs_auth, provide_verifier
import discogs_client

discogs_consumer_key, discogs_consumer_secret = provide_discogs_auth()
discogs = discogs_client.Client(user_agent="ThoughfulMachineLearning",
                                consumer_key=discogs_consumer_key,
                          consumer_secret=discogs_consumer_secret)
discogs_auth_url = discogs.get_authorize_url()
discogs.get_access_token(verifier=provide_verifier())
discogs.identity()

函数provide_discogs_authprovide_verifier只返回消费者密钥&来自用户授权的秘密和验证者。 get_access_token按预期返回访问密钥和密码。

然而,在最后一行,当我进行API调用时,我得到:

Out[38]: In[39]: discogs.identity()
Traceback (most recent call last):
Out[39]:   File "/usr/local/lib/python3.4/dist-packages/IPython/core/formatters.py", line 219, in catch_format_error
    r = method(self, *args, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/IPython/core/formatters.py", line 690, in __call__
    printer.pretty(obj)
  File "/usr/local/lib/python3.4/dist-packages/IPython/lib/pretty.py", line 407, in pretty
    return _default_pprint(obj, self, cycle)
  File "/usr/local/lib/python3.4/dist-packages/IPython/lib/pretty.py", line 527, in _default_pprint
    _repr_pprint(obj, p, cycle)
  File "/usr/local/lib/python3.4/dist-packages/IPython/lib/pretty.py", line 709, in _repr_pprint
    output = repr(obj)
TypeError: __repr__ returned non-string (type bytes)

不确定这是否与IPython或客户端库有关,但无论如何都会感谢帮助。谢谢。

1 个答案:

答案 0 :(得分:2)

这是图书馆的一个错误; {3}返回Python 3上的字节:

def __repr__(self):
    return '<User {0!r} {1!r}>'.format(self.id, self.username).encode('utf-8')

你已经User.__repr__ method了项目,这很棒!

您可以通过将discogs.identity()的结果分配给变量来避免在IPython或任何其他交互式Python控制台中看到的问题:

user = discogs.identity()

尽量避免回应结果。

您可以使用以下方法动态修补方法:

import six
from discogs_client import models

orig_repr = models.User.__repr__

def fixed_repr(self):
    r = orig_repr(self)
    if six.PY3 and isinstance(r, bytes):
        r = r.decode('utf8')
    return r

models.User.__repr__ = fixed_repr

您可能也必须为其他模型执行此操作;我在__repr__模块中看到了.encode('utf8')models次调用的实现。