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

本地运行AWS SAM时提示aws_lambda_powertools未找到的问题

解决方案:SAM本地运行无法导入aws_lambda_powertools

问题根源:部署到云端时,AWS会自动根据依赖文件安装包,但本地运行sam local start-api时,Lambda容器默认不会自动加载你本地环境的依赖,必须让依赖和代码一起被容器访问到。

以下是几种可行的解决方法:

方法1:直接将依赖安装到代码目录

在项目根目录执行命令,把依赖直接安装到Lambda代码所在的hello_world目录下:

pip install aws-lambda-powertools -t hello_world/

如果有requirements.txt文件,也可以用:

pip install -r requirements.txt -t hello_world/

执行完成后,hello_world目录下会出现aws_lambda_powertools相关的包文件,此时再运行sam local start-api -t template.yaml就能正常导入依赖。

方法2:通过SAM Build自动构建依赖(推荐)

修改你的SAM模板,在HelloWorldFunction资源下添加Metadata配置,指定Python版本的构建方法:

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.lambda_handler
      CodeUri: hello_world
      Description: Hello World function
      Architectures:
      - x86_64
      Tracing: Active
      Events:
        HelloPath:
          Type: Api
          Properties:
            Path: /hello
            Method: GET
    Metadata:
      BuildMethod: python3.12

然后执行以下命令构建项目:

sam build

SAM会自动创建一个.aws-sam目录,里面包含打包好的代码和依赖。之后再运行本地API服务:

sam local start-api -t template.yaml

这种方式能确保依赖和云端运行环境一致,避免架构或版本不兼容问题。

注意事项

  • 不要直接复制虚拟环境的site-packages目录到代码文件夹,可能会包含系统特定的依赖文件,导致本地运行出错。
  • 每次修改依赖或代码后,若使用SAM Build方式,需要重新执行sam build更新构建目录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 14:05:24