Python - 尝试使用意外的 mimetype 解码 JSON: [英] Python - Attempt to decode JSON with unexpected mimetype:

查看:29
本文介绍了Python - 尝试使用意外的 mimetype 解码 JSON:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I recently swapped over from requests to aiohttp because I couldn't use it in asyncio loops.

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

The swap went perfectly and everything goes well except for one thing. My console is full of

Attempt to decode JSON with unexpected mimetype:

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

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

My code has a list of sites it goes too and grabs JSON from, Each site is different but my loop is basically the same for each of them, Ive simplified it here:

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.但出于某种原因

It works perfectly, connects to the site grabs the json and sets endVariable correctly. but for some reason

Attempt to decode JSON with unexpected mimetype:

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

prints every time it goes through the loop. Which is annoying because it prints stats to the console and they get lost in the the errors each time it grabs a sites json

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

Is there a way to fix this error or to hide it?

推荐答案

aiohttp 正在尝试 做正确的事并警告您不正确的Content-Type,最坏的情况可能表明您根本没有获得JSON数据,但是一些无关的东西,例如错误页面的 HTML 内容.

aiohttp is trying to do the right thing and warn you of incorrect Content-Type, which could at worst indicate that you are not getting JSON data at all, but something unrelated, such as the HTML content of an error page.

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

However, in practice many servers are misconfigured to always send the incorrect MIME type in their JSON responses, and JavaScript libraries apparently don't care. If you know you're dealing with such a server, you can always silence the warning by invoking json.loads yourself:

import json
# ...

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

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

Specifying Content-Type as you attempted makes no difference because it only affects the Content-Type of your request, whereas the problem lies in the Content-Type of the server's response, which is not under your control.

这篇关于Python - 尝试使用意外的 mimetype 解码 JSON:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆