

# 使用 Python Lambda 函数的层
<a name="python-layers"></a>

使用 [Lambda 层](chapter-layers.md)来打包要在多个函数中重复使用的代码和依赖项。层通常包含库依赖项、[自定义运行时系统](runtimes-custom.md)或配置文件。创建层涉及三个常见步骤：

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

1. 在 Lambda 中创建层。

1. 将层添加到函数。

**Topics**
+ [

## 打包层内容
](#python-layers-package)
+ [

## 在 Lambda 中创建层
](#publishing-layer)
+ [

## 将层添加到函数
](#python-layer-adding)
+ [

## 示例应用程序
](#python-layer-sample-app)

## 打包层内容
<a name="python-layers-package"></a>

要创建层，请将您的包捆绑到满足以下要求的 .zip 文件存档中：
+ 使用计划用于 Lambda 函数的相同 Python 版本来构建层。例如，如果您使用 Python 3.14 构建层，则您的函数应使用 Python 3.14 运行时。
+ 您的 .zip 文件必须包含根级 `python` 目录。
+ 您的层中的包必须与 Linux 兼容。Lambda 函数在 Amazon Linux 上运行。

您可以创建包含使用 `pip` 安装的第三方 Python 库（例如 `requests` 或 `pandas`）或您自己的 Python 模块和包的层。

### 第三方依赖项
<a name="python-layers-third-party-dependencies"></a>

**使用 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 部署包](python-package.md#python-package-native-libraries)。

------
#### [ requirements.txt ]

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

**Example 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 部署包](python-package.md#python-package-native-libraries)。

------

1. 压缩 `python` 目录中的内容。

------
#### [ Linux/macOS ]

   ```
   zip -r layer.zip python/
   ```

------
#### [ PowerShell ]

   ```
   Compress-Archive -Path .\python -DestinationPath .\layer.zip
   ```

------

   您的 .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 就可以找到并导入您的包。

### 自定义 Python 模块
<a name="custom-python-modules"></a>

**使用您自己的代码创建层**

1. 为您的层创建所需的顶级目录：

   ```
   mkdir python
   ```

1. 在 `python` 目录中创建您的 Python 模块。以下示例模块通过确认订单包含所需信息来验证订单。  
**Example 自定义模块：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)
       }
   ```

1. 压缩 `python` 目录中的内容。

------
#### [ Linux/macOS ]

   ```
   zip -r layer.zip python/
   ```

------
#### [ PowerShell ]

   ```
   Compress-Archive -Path .\python -DestinationPath .\layer.zip
   ```

------

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

   ```
   python/     # Required top-level directory
   └── validator.py
   ```

1. 在您的函数中，像处理任何 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'
           })
   ```

   您可以使用以下[测试事件](testing-functions.md#invoke-with-event)调用函数：

   ```
   {
       "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 中创建层
<a name="publishing-layer"></a>

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

------
#### [ AWS CLI ]

运行 [publish-layer-version](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/publish-layer-version.html) AWS CLI 命令以创建 Lambda 层：

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

[兼容的运行时](https://docs.aws.amazon.com/lambda/latest/api/API_PublishLayerVersion.html#lambda-PublishLayerVersion-request-CompatibleRuntimes)参数是可选的。指定后，Lambda 将使用此参数在 Lambda 控制台中筛选层。

------
#### [ Console ]

**创建层（控制台）**

1. 打开 Lambda 控制台的 [Layers page](https://console.aws.amazon.com/lambda/home#/layers)（层页面）。

1. 选择 **Create layer**（创建层）。

1. 选择**上传 .zip 文件**，然后上传您之前创建的 .zip 存档。

1. （可选）对于**兼容的运行时**，请选择与您用于构建层的 Python 版本相对应的 Python 运行时。

1. 选择**创建**。

------

## 将层添加到函数
<a name="python-layer-adding"></a>

------
#### [ AWS CLI ]

要将层附加到函数，请运行 [update-function-configuration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/update-function-configuration.html) AWS CLI 命令。对于 `--layers` 参数，使用层 ARN。ARN 必须指定版本（例如 `arn:aws:lambda:us-east-1:123456789012:layer:my-layer:1`）。有关更多信息，请参阅 [层和层版本](chapter-layers.md#lambda-layer-versions)。

```
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"
```

如果使用 **cli-binary-format** 版本 2，则 AWS CLI 选项是必需的。要将其设为默认设置，请运行 `aws configure set cli-binary-format raw-in-base64-out`。有关更多信息，请参阅*版本 2 的 AWS Command Line Interface 用户指南*中的 [AWS CLI 支持的全局命令行选项](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-options.html#cli-configure-options-list)。

------
#### [ Console ]

**向函数添加层**

1. 打开 Lamba 控制台的[函数](https://console.aws.amazon.com/lambda/home#/functions)页面。

1. 选择函数。

1. 向下滚动到**层**部分，然后选择**添加层**。

1. 在**选择层**下，选择**自定义层**，然后选择您的层。
**注意**  
如果您在创建层时没有添加[兼容的运行时](https://docs.aws.amazon.com/lambda/latest/api/API_PublishLayerVersion.html#lambda-PublishLayerVersion-request-CompatibleRuntimes)，则您的层将不会在此处列出。您可以改为指定层 ARN。

1. 选择**添加**。

------

## 示例应用程序
<a name="python-layer-sample-app"></a>

有关如何使用 Lambda 层的更多示例，请参阅 AWS Lambda Developer Guide GitHub 存储库中的 [layer-python](https://github.com/awsdocs/aws-lambda-developer-guide/tree/main/sample-apps/layer-python) 示例应用程序。此应用程序包括两个包含 Python 库的层。创建层后，即可部署并调用相应的函数来确认层是否按预期运行。