【问题标题】:Python - Attempt to decode JSON with unexpected mimetype:Python - 尝试使用意外的 mimetype 解码 JSON:
【发布时间】:2018-02-17 10:33:06
【问题描述】:

我最近从 requests 切换到 aiohttp,因为我无法在 asyncio 循环中使用它。

交换进行得很顺利,除了一件事,一切都很顺利。我的控制台充满了

Attempt to decode JSON with unexpected mimetype:

Attempt to decode JSON with unexpected mimetype: txt/html; charset=utf-8

我的代码有一个站点列表,它也可以从中获取 JSON,每个站点都不同,但每个站点的循环基本相同,我在这里对其进行了简化:

PoolName = "http://website.com"
endpoint = "/api/stats"
headers = "headers = {'content-type': 'text/html'}" #Ive tried "application/json" and no headers
async with aiohttp.get(url=PoolName+endpoint, headers=headers) as hashrate:
                hashrate = await hashrate.json()
endVariable = hashrate['GLRC']['HASH']

它运行良好,连接到站点抓取 json 并正确设置 endVariable。但由于某种原因

Attempt to decode JSON with unexpected mimetype:

在每次循环时打印。这很烦人,因为它将统计信息打印到控制台,并且每次抓取站点 json 时它们都会迷失在错误中

有没有办法修复或隐藏此错误?

【问题讨论】:

    标签: python json python-3.x python-asyncio aiohttp


    【解决方案1】:

    将预期的内容类型传递给json() 方法:

    data = await resp.json(content_type='text/html')
    

    或完全禁用检查:

    data = await resp.json(content_type=None)
    

    【讨论】:

    • ➕1,我不知道你可以关闭检查或自定义预期的标题。
    【解决方案2】:

    aiohttp 正在尝试 do the right thing and warn you 不正确的 Content-Type,这可能表明您根本没有获得 JSON 数据,而是一些不相关的东西,例如错误页面的 HTML 内容。

    然而,实际上许多服务器被错误配置为总是在其 JSON 响应中发送不正确的 MIME 类型,而 JavaScript 库显然不在乎。如果您知道您正在处理这样的服务器,您可以随时通过自己调用 json.loads 来消除警告:

    import json
    # ...
    
    async with self._session.get(uri, ...) as resp:
        data = await resp.read()
    hashrate = json.loads(data)
    

    在您尝试时指定Content-Type 没有区别,因为它只会影响您的请求Content-Type,而问题在于服务器的响应Content-Type em>,这不在你的控制之下。

    【讨论】:

      猜你喜欢
      • 2021-09-30
      • 1970-01-01
      • 2013-10-25
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多