Python - 尝试使用意外的 mimetype 解码 JSON:

Python - Attempt to decode JSON with unexpected mimetype:

我最近从请求切换到 aiohttp,因为我不能在异步循环中使用它。

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

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

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

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 服务器的 响应 ,这不受您的控制。

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

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

或完全禁用检查:

data = await resp.json(content_type=None)