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

Puf*_*ses 7 python json python-3.x python-asyncio aiohttp

我最近从请求交换到aiohttp,因为我无法在asyncio循环中使用它.

交换完美,一切顺利,除了一件事.我的控制台充满了

Attempt to decode JSON with unexpected mimetype:
Run Code Online (Sandbox Code Playgroud)

Attempt to decode JSON with unexpected mimetype: txt/html; charset=utf-8
Run Code Online (Sandbox Code Playgroud)

我的代码也有一个网站列表,它也可以抓取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']
Run Code Online (Sandbox Code Playgroud)

它工作得很好,连接到站点抓取json并正确设置endVariable.但出于某种原因

Attempt to decode JSON with unexpected mimetype:
Run Code Online (Sandbox Code Playgroud)

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

有没有办法解决这个错误或隐藏它?

And*_*lov 17

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

data = await resp.json(content_type='text/html')
Run Code Online (Sandbox Code Playgroud)

或完全禁用检查:

data = await resp.json(content_type=None)
Run Code Online (Sandbox Code Playgroud)

  • ➕1,我不知道你可以关闭检查或自定义预期的标题。 (3认同)

use*_*342 14

aiohttp正在尝试做正确的事情并警告你不正确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)
Run Code Online (Sandbox Code Playgroud)

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