分层 Lambda:AWS SAM 和 Python

适度的代码复用总是有益的。

目录

以下是关于如何向AWS Lambda添加层的逐步说明 - 使用Python。 将使用标准的HelloWorld模板示例生成的基础代码。

letters-layers

当然,你也需要安装并配置好所有Python 和AWS SAM相关工具 预安装

生成并运行示例项目

现在调用 sam init 并以标准方式回答问题,如下所示:

sam-init-answers

它将显示摘要:

sam-init-summary

并创建具有结构和一些文件的项目文件夹。template.yaml 是非常标准的。

vs-code-template-yaml

以及函数代码(我将清理掉多余的生成注释):

import json

def lambda_handler(event, context):

    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello world",
            # "location": ip.text.replace("\n", "")
        }),
    }

现在让我们在本地构建并调用这个函数:

sam validate && sam build --use-container && sam local invoke HelloWorldFunction --event events/event.json

响应的结尾应该类似于以下内容:

.....
START RequestId: 6da35464-7c6a-40b2-bcc0-60796994317a Version: $LATEST
END RequestId: 737ae28d-2b99-49e6-baae-40ab9bb99599
REPORT RequestId: 737ae28d-2b99-49e6-baae-40ab9bb99599  Init Duration: 0.04 ms  Duration: 28.40 ms      Billed Duration: 29 ms  Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode": 200, "body": "{\"message\": \"hello world\"}"}

添加层

在 template.yaml 中添加层描述

两部分:

  • ApiSharedLayer - 描述它的块
  • Layers: … - !Ref ApiSharedLayer - 在使用它的函数中
.....
Resources:
# added code start
    ApiSharedLayer:
        Type: AWS::Serverless::LayerVersion
        Properties:
            ContentUri: api_shared_layer/
            LayerName: api-shared-layer
            Description: My api-shared-layer
            CompatibleRuntimes:
                - python3.9
            RetentionPolicy: Delete                
        Metadata:
            BuildMethod: python3.9   # Required to have AWS SAM build this layer
# added code end

  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
        - x86_64
# added code start
      Layers:
        - !Ref ApiSharedLayer
# added code end
      Events:
.....

添加层代码

在文件夹 api_shared_layer 中添加一些代码:

layer code

更新函数以使用此代码

import json
from api_version import API_VERSION

def lambda_handler(event, context):

    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello world",
            "version": API_VERSION
        }),
    }

测试运行

再次运行:

sam validate && sam build --use-container && sam local invoke HelloWorldFunction --event events/event.json

响应的结尾应该类似于以下内容:

.....
START RequestId: 88eb1887-ae94-479d-a059-f87c4b71a282 Version: $LATEST
END RequestId: 927f7d05-4d13-44ba-9377-03e6d3e8bacf
REPORT RequestId: 927f7d05-4d13-44ba-9377-03e6d3e8bacf  Init Duration: 0.72 ms  Duration: 34.80 ms      Billed Duration: 35 ms  Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode": 200, "body": "{\"message\": \"hello world\", \"version\": \"1.1.1\"}"}

很好。

有用的链接