使用Lambda与Docker部署FastAPI时出现KeyError: 'path'错误求助
FastAPI部署AWS Lambda(Docker方式)出现KeyError: 'path'问题
错误日志
OpenBLAS WARNING - could not determine the L2 cache size on this system, assuming 256k OpenBLAS WARNING - could not determine the L2 cache size on this system, assuming 256k START RequestId: afcef2d3-c9fe-47f8-834e-fb57c450e6f3 Version: $LATEST [INFO] 2022-11-13T22:55:34.944Z afcef2d3-c9fe-47f8-834e-fb57c450e6f3 Waiting for application startup. [INFO] 2022-11-13T22:55:34.944Z afcef2d3-c9fe-47f8-834e-fb57c450e6f3 LifespanCycleState.STARTUP: 'lifespan.startup.complete' event received from application. [INFO] 2022-11-13T22:55:34.944Z afcef2d3-c9fe-47f8-834e-fb57c450e6f3 Application startup complete. [INFO] 2022-11-13T22:55:34.945Z afcef2d3-c9fe-47f8-834e-fb57c450e6f3 Waiting for application shutdown. [INFO] 2022-11-13T22:55:34.945Z afcef2d3-c9fe-47f8-834e-fb57c450e6f3 LifespanCycleState.SHUTDOWN: 'lifespan.shutdown.complete' event received from application. [ERROR] KeyError: 'path' Traceback (most recent call last): File "/var/task/app.py", line 34, in handler response = asgi_handler(event, context) File "/var/task/mangum/adapter.py", line 101, in __call__ scope = self.create_scope(event, context) File "/var/task/mangum/adapter.py", line 148, in create_scope path = event["path"] END RequestId: afcef2d3-c9fe-47f8-834e-fb57c450e6f3 REPORT RequestId: afcef2d3-c9fe-47f8-834e-fb57c450e6f3 Duration: 12529.69 ms Billed Duration: 12530 ms Memory Size: 512 MB Max Memory Used: 163 MB
项目结构
-app ---routes/ ---__init__.py ---app.py -Dockerfile -package.json -requirements.txt -serverless.yaml
核心代码
app.py
import uvicorn import os from fastapi import FastAPI from mangum import Mangum from routes import main stage = os.environ.get('STAGE', None) openapi_prefix = f"/{stage}" if stage else "/" app = FastAPI(title = "XX", description = "XX", root_path=openapi_prefix ) app.include_router(main.router, prefix='/metrics', tags=['metrics']) def handler(event, context): event['requestContext'] = {} # Adds a dummy field; mangum will process this fine asgi_handler = Mangum(app) response = asgi_handler(event, context) return response if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=5000)
Dockerfile
FROM public.ecr.aws/lambda/python:3.8 # Copy function code COPY ./app ${LAMBDA_TASK_ROOT} # Install the function's dependencies using file requirements.txt # from your project folder. COPY ./requirements.txt . RUN pip3 install -r requirements.txt --target "${LAMBDA_TASK_ROOT}" -U --no-cache-dir # Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile) CMD [ "app.handler" ]
问题背景
非Docker方式部署FastAPI到Lambda时一切正常,但改用Docker镜像部署后,Handler持续抛出KeyError: 'path',无法完成请求处理。
解决方案
- 规范Lambda测试事件结构
Mangum依赖API Gateway格式的事件数据,直接在Lambda控制台测试时,默认事件可能缺少path字段。需手动补充完整的事件结构,示例:
{ "path": "/metrics", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, "requestContext": {} }
- 优化Handler初始化逻辑
避免在每次请求中重复创建Mangum实例,将实例化代码移到Handler函数外部,同时增加字段检查:
# 移到handler外,全局初始化一次 asgi_handler = Mangum(app) def handler(event, context): # 确保事件包含必要字段 event.setdefault('path', '/') event.setdefault('requestContext', {}) response = asgi_handler(event, context) return response
升级Mangum版本
旧版Mangum对Docker部署的Lambda事件兼容性较差,在requirements.txt中指定最新稳定版本(如mangum>=0.17.0),重新构建镜像。验证Docker文件复制路径
确认COPY ./app ${LAMBDA_TASK_ROOT}命令正确将app目录下所有文件复制到/var/task,避免因文件缺失导致的间接异常。
内容的提问来源于stack exchange,提问作者Jose Luis Rangel
相关产品推荐
相关产品推荐

