【问题标题】:httplib2.Http() - TypeError: the JSON object must be str, not 'bytes'httplib2.Http() - TypeError:JSON 对象必须是 str,而不是 'bytes'
【发布时间】:2023-03-13 16:10:01
【问题描述】:

此代码在 Python2 中完美运行,但在 Python3 中却不行。我经历了很多可能的解决方案,但没有一个。他们似乎工作。我怎样才能做到这一点。在 python3 中工作?

错误日志:

[Tue Jul 10 07:23:21.713813 2018] [wsgi:error] [pid 1667:tid 140651010107136]
    h = httplib2.Http()

[Tue Jul 10 07:23:21.713843 2018] [wsgi:error] [pid 1667:tid 140651010107136]
    File "/usr/lib/python3.5/json/__init__.py", line 312, in loads

[Tue Jul 10 07:23:21.713874 2018] [wsgi:error] [pid 1667:tid 140651010107136]
    s.__class__.__name__))

[Tue Jul 10 07:23:21.713907 2018] [wsgi:error] [pid 1667:tid 140651010107136]
    TypeError: the JSON object must be str, not 'bytes'

代码:

# Check that the access token is valid.
access_token = credentials.access_token
url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
       % access_token)
h = httplib2.Http()
result = json.loads(h.request(url, 'GET')[1])
# If there was an error in the access token info, abort.
if result.get('error') is not None:
    response = make_response(json.dumps(result.get('error')), 500)
    response.headers['Content-Type'] = 'application/json'
    return response

【问题讨论】:

    标签: python json python-3.x python-2.x httplib2


    【解决方案1】:

    这在the docs for the http2lib library:

    “内容”是从 URL 检索到的内容。如有必要,内容已经解压缩或解压缩。 'resp' 包含所有响应头。

    Python 3 区分了字节和字符串。在 httplib2 中,响应头是字符串,但内容是字节。如果要将内容转为字符串,则需要determine the character encoding,然后显式转换为字符串。执行此操作的确切算法取决于媒体类型; httplib2 无法帮你判断字符编码。

    一旦确定了字符编码,剩下的就很简单了。例如,如果您确定编码是 UTF-8,您会说:

    str_content = content.decode('utf-8')
    

    换句话说,您需要编写代码来解析 HTTP 标头、HTML meta 标记等,以找出字符编码(加上任何回退到类似 chardetUnicode, Damnit 或其他启发式你想要的库),然后decode内容,然后你可以json.loads结果。


    话虽如此,几乎所有提供 JSON 服务的服务器都可能提供 UTF-8 或纯 ASCII 码,所有非 ASCII 码都进行了转义,其中任何一个当然都可以解码为 UTF-8。这是 3.x 最新版本中的默认编码,因此,如果“几乎”对您来说足够好,只需在内容中添加一个 .decode(),然后再调用 json.loads,它几乎可以在所有服务器上运行.


    或者您可以切换到像requests 这样的库,它会为您完成读取编码和应用它的所有工作,因此您只需执行json.load(r.text)。或者你甚至可以让它为你做 JSON 解码,然后做r.json()

    【讨论】:

      【解决方案2】:

      这对我有用。 result = json.loads((h.request(url, 'GET')[1]).decode()) 记住每次编辑代码时都要重新加载服务器。 正如我发现的那样,它并不总是能捡起它。使用它在 AWS Lightsail 上进行部署。

      【讨论】:

      • 天哪,从 python 2.7 更改为 python 3.5 后,我花了几个小时试图完成这项工作,非常感谢!
      猜你喜欢
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 2017-08-11
      • 2019-10-10
      • 2017-11-01
      • 2018-04-26
      • 1970-01-01
      相关资源
      最近更新 更多