从requests切换至aiohttp后控制台频繁输出JSON解码MIME类型异常提示
解决aiohttp中「Attempt to decode JSON with unexpected mimetype」警告的问题
这个问题我之前也碰到过!其实是aiohttp默认的JSON解码逻辑在搞鬼——它会严格校验响应的Content-Type头,哪怕返回的内容明明是合法JSON,只要头不是application/json(或类似的JSON类型),就会弹出这个警告。虽然不影响功能,但控制台刷满提示确实闹心,给你几个实用的解决办法:
方案1:直接过滤特定警告
如果不想改业务代码,最简单的方式就是用Python的warnings模块把这个警告屏蔽掉,放在代码开头就行:
import warnings # 精准匹配警告信息,只过滤这一条 warnings.filterwarnings("ignore", message="Attempt to decode JSON with unexpected mimetype")
方案2:手动解码响应文本(最灵活)
绕过aiohttp的自动校验逻辑,自己读取响应文本再用json.loads()解析,完全不受Content-Type限制:
import json import asyncio from aiohttp import ClientSession async def fetch_site(session, url): async with session.get(url) as response: # 先获取文本内容,再手动解析JSON response_text = await response.text() data = json.loads(response_text) # 这里处理你的业务逻辑,比如设置endVariable return data async def main(): sites = ["https://example1.com/api", "https://example2.com/data"] async with ClientSession() as session: tasks = [fetch_site(session, url) for url in sites] await asyncio.gather(*tasks) asyncio.run(main())
方案3:修改response.json()的参数(最简洁)
aiohttp的json()方法其实支持跳过Content-Type校验,只需要传入content_type=None参数:
import asyncio from aiohttp import ClientSession async def fetch_site(session, url): async with session.get(url) as response: # 告诉aiohttp不要校验Content-Type,直接解码 data = await response.json(content_type=None) # 处理业务逻辑 return data async def main(): sites = ["https://example1.com/api", "https://example2.com/data"] async with ClientSession() as session: tasks = [fetch_site(session, url) for url in sites] await asyncio.gather(*tasks) asyncio.run(main())
额外小技巧:严谨性兼顾
如果担心有些站点返回的不是JSON,可以先检查Content-Type头,再选择解码方式:
import json async def fetch_site(session, url): async with session.get(url) as response: content_type = response.headers.get("Content-Type", "").lower() if "json" in content_type: data = await response.json() else: # 非JSON类型的响应做容错处理 try: data = json.loads(await response.text()) except json.JSONDecodeError: # 处理解析失败的情况 data = None return data
选一个适合你场景的方案就行,我个人常用方案3,代码改动最小,又能解决警告问题~
内容的提问来源于stack exchange,提问作者pfych
相关产品推荐
相关产品推荐

