You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lambda容器函数用aioboto3报错:找不到botocore.compress模块

容器化Lambda函数报错:No module named 'botocore.compress'

问题重现

使用以下配置构建容器化Lambda函数时,本地或线上调用均触发Runtime.ImportModuleError:

Dockerfile

FROM public.ecr.aws/lambda/python:3.10

COPY requirements.txt .
RUN pip install -r requirements.txt
RUN pip install --upgrade boto3 # Just to be safe
RUN pip install --upgrade botocore # Just to be safe

COPY ./main.py ${LAMBDA_TASK_ROOT}

CMD ["main.lambda_handler"]

main.py

import asyncio
import aioboto3


def lambda_handler(event, context):
    key = "test"
    bucket = "test"
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(test_key(bucket, key))
    return result


async def test_key(bucket: str, key: str):
    try:
        session = aioboto3.Session()
        async with session.client("s3") as client:
            response = await client.head_object(Bucket=bucket, Key=key)
            return True
    except Exception as e:
        return False

requirements.txt

aioboto3
asyncio

报错信息

{"errorMessage": "Unable to import module 'main': No module named 'botocore.compress'", "errorType": "Runtime.ImportModuleError", "requestId": "87dcc2be-d84c-4725-8f2f-663219c6f43c", "stackTrace": []}

问题原因

Lambda官方Python镜像(public.ecr.aws/lambda/python:3.10)已预装适配Lambda环境的boto3和botocore版本。手动执行pip install --upgrade boto3/botocore会覆盖原有依赖,导致新版本botocore的模块结构与aioboto3依赖的版本不兼容,进而出现botocore.compress模块缺失的问题。

解决方案

  1. 移除不必要的依赖升级命令
    修改Dockerfile,删除RUN pip install --upgrade boto3和RUN pip install --upgrade botocore两行,保留基础镜像自带的适配版本:

    FROM public.ecr.aws/lambda/python:3.10
    
    COPY requirements.txt .
    RUN pip install -r requirements.txt
    
    COPY ./main.py ${LAMBDA_TASK_ROOT}
    
    CMD ["main.lambda_handler"]
    
  2. 锁定aioboto3的兼容版本
    在requirements.txt中指定与Lambda基础镜像botocore兼容的aioboto3版本(比如v12.x系列,适配稳定的botocore版本):

    aioboto3~=12.0.0
    asyncio
    
  3. 重新构建并测试镜像
    执行以下命令重新构建容器镜像并测试:

    docker build -t lambda-aioboto3 .
    # 本地测试可使用Lambda Runtime Interface Emulator
    docker run -p 9000:8080 lambda-aioboto3
    # 另开终端调用测试
    curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{}'
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 17:56:19