You need to enable JavaScript to run this app. Python asyncio获取S3 gzip文件报ContentTypeError及TypeError问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Python asyncio获取S3 gzip文件报ContentTypeError及TypeError问题求助

错误原因

  1. 首次调用resp.json()报错:S3返回的gzip文件响应头Content-Type为application/octet-stream,aiohttp的json()方法默认校验mimetype与JSON类型不匹配,直接抛出ContentTypeError。
  2. 二次修改后报错:resp.content是aiohttp的流式读取对象StreamReader,不是同步requests中直接返回的字节内容,无法直接传入gzip.decompress处理,需要先异步读取完整字节内容。

完整可运行修改代码

import asyncio
import aiohttp
import gzip
import json
import time
import nest_asyncio

async def get_data(session, url, headers):
    async with session.get(url, headers=headers) as resp:
        # 异步读取全部响应字节
        content_bytes = await resp.read()
        # 解压gzip压缩内容
        decompressed_content = gzip.decompress(content_bytes)
        # 解析为JSON对象
        return json.loads(decompressed_content)
  
async def main(req_url, headers):
    async with aiohttp.ClientSession() as session:
        tasks = [get_data(session, req_url, headers)]
        data = await asyncio.gather(*tasks)
        # 若只有单个任务,可直接return data[0]去掉外层列表
        return data

# 替换为你实际的请求头与S3文件地址
headers = {}
location = "你的S3文件访问地址"

start_time1 = time.time()
nest_asyncio.apply()
keyword_list = asyncio.run(main(location, headers))
print("--- %s seconds ---" % (time.time() - start_time1))

核心修改点

  • 新增await resp.read()异步读取全部响应字节,得到bytes类型数据后再传入解压方法处理
  • 修复原main函数无返回值的问题,避免最终拿到的keyword_list为None
  • 简化任务创建逻辑,无需显式调用asyncio.ensure_future,直接传入协程对象到asyncio.gather即可正常调度执行

内容的提问来源于stack exchange,提问作者Prasand Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 11:51:01