

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 針對 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 建置 layer，請使用適用於函數的 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 主控台發佈 layer。

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

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

```
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 主控台中的 [層頁面](https://console.aws.amazon.com/lambda/home#/layers)。

1. 選擇 **建立圖層**。

1. 選擇**上傳 .zip 檔案**，然後上傳先前建立的 .zip 壓縮檔。

1. (選用) 在**相容的執行時期**欄位中，選擇與用於建置層的 Python 版本相對應的 Python 執行時期。

1. 選擇**建立**。

------

## 將層新增至函式
<a name="python-layer-adding"></a>

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

若要將 layer 連接至函數，請執行 [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"
```

如果您使用的是第 2 AWS CLI 版，則需要 **cli-binary-format**選項。若要讓此成為預設的設定，請執行 `aws configure set cli-binary-format raw-in-base64-out`。若要取得更多資訊，請參閱*《AWS Command Line Interface 使用者指南第 2 版》*中 [AWS CLI 支援的全域命令列選項](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-options.html#cli-configure-options-list)。

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

**將層新增至函式**

1. 開啟 Lambda 主控台中的[函數頁面](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 開發人員指南 GitHub 儲存庫》中的 [layer-python](https://github.com/awsdocs/aws-lambda-developer-guide/tree/main/sample-apps/layer-python) 範例應用程式。此應用程式包含兩個內含 Python 程式庫的層。建立層之後，您可以部署並調用對應的函式，驗證層是否如預期運作。