使用 Python Lambda 函数的层 - Amazon Lambda
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

使用 Python Lambda 函数的层

使用 Lambda 层来打包要在多个函数中重复使用的代码和依赖项。层通常包含库依赖项、自定义运行时系统或配置文件。创建层涉及三个常见步骤:

  1. 打包层内容。此步骤需要创建 .zip 文件存档,其中包含要在函数中使用的依赖项。

  2. 在 Lambda 中创建层。

  3. 将层添加到函数。

本主题说明如何创建 Python 层并将其附加到 Lambda 函数。

打包层内容

要创建层,请将您的包捆绑到满足以下要求的 .zip 文件存档中:

  • 使用计划用于 Lambda 函数的相同 Python 版本来构建层。例如,如果您使用 Python 3.13 构建层,则您的函数应使用 Python 3.13 运行时。

  • 您的 .zip 文件必须包含根级 python 目录。

  • 您的层中的包必须与 Linux 兼容。Lambda 函数在 Amazon Linux 上运行。

您可以创建包含使用 pip 安装的第三方 Python 库(例如 requestspandas)或您自己的 Python 模块和包的层。

使用 pip 包创建层
  1. 选择以下方法之一,将 pip 包安装到所需的顶级目录(python/):

    pip install

    对于纯 Python 包(如 requests 或 boto3):

    pip install requests -t python/

    某些 Python 包(如 NumPy 和 Pandas)包含编译后的 C 组件。如果您要在 macOS 或 Windows 上使用这些包构建层,则可能需要使用以下命令来安装兼容 Linux 的 wheel 包:

    pip install numpy --platform manylinux2014_x86_64 --only-binary=:all: -t python/

    有关使用包含已编译组件的 Python 包的更多信息,请参阅使用原生库创建 .zip 部署包

    requirements.txt

    使用 requirements.txt 文件可以帮助您管理包版本并确保安装的一致性。

    例 requirements.txt
    requests==2.31.0 boto3==1.37.34 numpy==1.26.4

    如果您的 requirements.txt 文件只包含纯 Python 包(如 requests 或 boto3):

    pip install -r requirements.txt -t python/

    某些 Python 包(如 NumPy 和 Pandas)包含编译后的 C 组件。如果您要在 macOS 或 Windows 上使用这些包构建层,则可能需要使用以下命令来安装兼容 Linux 的 wheel 包:

    pip install -r requirements.txt --platform manylinux2014_x86_64 --only-binary=:all: -t python/

    有关使用包含已编译组件的 Python 包的更多信息,请参阅使用原生库创建 .zip 部署包

  2. 压缩 python 目录中的内容。

    zip -r layer.zip python/

    您的 .zip 文件的目录结构应如下所示:

    python/              # Required top-level directory
    └── requests/
    └── boto3/
    └── numpy/
    └── (dependencies of the other packages)
    注意

    如果您使用 Python 虚拟环境(venv)来安装包,则目录结构将有所不同(例如,python/lib/python3.x/site-packages)。只要您的 .zip 文件包含根级 python 目录,Lambda 就可以找到并导入您的包。

使用您自己的代码创建层
  1. 为您的层创建所需的顶级目录:

    mkdir python
  2. python 目录中创建您的 Python 模块。以下示例模块通过确认订单包含所需信息来验证订单。

    例 自定义模块:validator.py
    import json def validate_order(order_data): """Validates an order and returns formatted data.""" required_fields = ['product_id', 'quantity'] # Check required fields missing_fields = [field for field in required_fields if field not in order_data] if missing_fields: raise ValueError(f"Missing required fields: {', '.join(missing_fields)}") # Validate quantity quantity = order_data['quantity'] if not isinstance(quantity, int) or quantity < 1: raise ValueError("Quantity must be a positive integer") # Format and return the validated data return { 'product_id': str(order_data['product_id']), 'quantity': quantity, 'shipping_priority': order_data.get('priority', 'standard') } def format_response(status_code, body): """Formats the API response.""" return { 'statusCode': status_code, 'body': json.dumps(body) }
  3. 压缩 python 目录中的内容。

    zip -r layer.zip python/

    您的 .zip 文件的目录结构应如下所示:

    python/     # Required top-level directory
    └── validator.py
  4. 在您的函数中,像处理任何 Python 包一样导入和使用这些模块。示例:

    from validator import validate_order, format_response import json def lambda_handler(event, context): try: # Parse the order data from the event body order_data = json.loads(event.get('body', '{}')) # Validate and format the order validated_order = validate_order(order_data) return format_response(200, { 'message': 'Order validated successfully', 'order': validated_order }) except ValueError as e: return format_response(400, { 'error': str(e) }) except Exception as e: return format_response(500, { 'error': 'Internal server error' })

    您可以使用以下测试事件调用函数:

    { "body": "{\"product_id\": \"ABC123\", \"quantity\": 2, \"priority\": \"express\"}" }

    预期的回应:

    { "statusCode": 200, "body": "{\"message\": \"Order validated successfully\", \"order\": {\"product_id\": \"ABC123\", \"quantity\": 2, \"shipping_priority\": \"express\"}}" }

在 Lambda 中创建层

您可以使用 Amazon CLI 或 Lambda 控制台发布层。

Amazon CLI

运行 publish-layer-version Amazon CLI 命令以创建 Lambda 层:

aws lambda publish-layer-version \ --layer-name my-layer \ --zip-file fileb://layer.zip \ --compatible-runtimes python3.13

兼容的运行时参数是可选的。指定后,Lambda 将使用此参数在 Lambda 控制台中筛选层。

Console
创建层(控制台)
  1. 打开 Lambda 控制台的 Layers page(层页面)。

  2. 选择 Create layer(创建层)。

  3. 选择上传 .zip 文件,然后上传您之前创建的 .zip 存档。

  4. (可选)对于兼容的运行时,请选择与您用于构建层的 Python 版本相对应的 Python 运行时。

  5. 选择创建

将层添加到函数

Amazon CLI

要将层附加到函数,请运行 update-function-configuration Amazon CLI 命令。对于 --layers 参数,使用层 ARN。ARN 必须指定版本(例如 arn:aws:lambda:us-east-1:123456789012:layer:my-layer:1)。有关更多信息,请参阅 层和层版本

aws lambda update-function-configuration \ --function-name my-function \ --cli-binary-format raw-in-base64-out \ --layers "arn:aws:lambda:us-east-1:123456789012:layer:my-layer:1"
Console
向函数添加层
  1. 打开 Lamba 控制台的函数页面

  2. 选择函数。

  3. 向下滚动到部分,然后选择添加层

  4. 选择层下,选择自定义层,然后选择您的层。

    注意

    如果您在创建层时没有添加兼容的运行时,则您的层将不会在此处列出。您可以改为指定层 ARN。

  5. 选择添加

示例应用程序

有关如何使用 Lambda 层的更多示例,请参阅 Amazon Lambda Developer Guide GitHub 存储库中的 layer-python 示例应用程序。此应用程序包括两个包含 Python 库的层。创建层后,即可部署并调用相应的函数来确认层是否按预期运行。