本地测试AWS Lambda FastAPI代码遇错误:无法推断事件处理程序
问题:本地测试AWS Lambda部署代码时触发事件处理推断错误
错误信息:适配器无法推断要用于该事件的处理程序,这可能与Lambda函数的调用方式有关
代码与测试命令
app.py
from pydantic import BaseModel from fastapi import FastAPI from mangum import Mangum from fastapi.responses import JSONResponse import uvicorn app=FastAPI() handler=Mangum(app) class TextModel(BaseModel): text: str @app.post("/") def process_data(text: TextModel): return JSONResponse({'result':text.text}) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=9000)
Dockerfile
FROM public.ecr.aws/lambda/python:3.11 COPY app.py ${LAMBDA_TASK_ROOT}/ COPY requirements.txt . RUN pip3 install -r requirements.txt --target "${LAMBDA_TASK_ROOT}" -U #--no-cache-dir CMD [ "app.handler" ]
本地测试命令
curl "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{"text":"hello world!"}'
问题原因与解决办法
核心原因
你用Lambda Runtime Emulator的调用端点测试时,发送的原始JSON不符合Lambda事件规范,Mangum适配器无法识别这种格式的事件。Lambda通过API网关触发时,事件是包含HTTP请求元数据的特定结构,不是直接传请求体。
解决步骤
1. 按Lambda API网关事件格式构造请求
修改curl命令,把请求数据包装成API网关事件结构:
curl "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{ "httpMethod": "POST", "path": "/", "headers": { "Content-Type": "application/json" }, "body": "{\"text\":\"hello world!\"}" }'
2. 直接用FastAPI原生方式测试
如果只是验证接口逻辑,不用通过Lambda模拟器,直接运行python app.py启动服务,然后用普通curl请求:
curl "http://localhost:9000/" -H "Content-Type: application/json" -d '{"text":"hello world!"}'
3. 版本适配检查(可选)
确保requirements.txt中Mangum和FastAPI版本兼容,比如最新版Mangum适配FastAPI 0.100+,版本不匹配也可能引发异常。
内容的提问来源于stack exchange,提问作者Talha Anwar
相关产品推荐
相关产品推荐

