針對 Python Lambda 函數使用層 - AWS Lambda

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

針對 Python Lambda 函數使用層

使用 Lambda 層來封裝您要在多個函數之間重複使用的程式碼和相依性。層通常具備程式庫相依性、自訂執行期或組態檔案。建立層包含三個一般步驟:

  1. 封裝層內容。這表示建立 .zip 封存檔,其中包含您要在函數中使用的相依項。

  2. 在 Lambda 中建立層。

  3. 將層新增至函數中。

本主題說明如何建立 Python layer 並將其連接至 Lambda 函數。

封裝層內容

若要建立 layer,請將套件綁定到符合下列要求的 .zip 檔案封存中:

  • 使用您計劃用於 Lambda 函數的相同 Python 版本建置 layer。例如,如果您使用 Python 3.13 建置 layer,請使用適用於函數的 Python 3.13 執行時間。

  • 您的 .zip 檔案必須包含根層級的python目錄。

  • 層中的套件必須與 Linux 相容。Lambda 函數會在 Amazon Linux 上執行。

您可以建立層,其中包含與 pip(例如 requestspandas) 一起安裝的第三方 Python 程式庫,或是您自己的 Python 模組和套件。

使用 pip 套件建立圖層
  1. 選擇下列其中一種方法,將pip套件安裝到所需的頂層目錄 (python/):

    pip install

    對於純 Python 套件 (例如 請求或 boto3):

    pip install requests -t python/

    有些 Python 套件,例如 NumPy 和 Pandas,包括編譯的 C 元件。如果您要在 macOS 或 Windows 上使用這些套件建置 layer,您可能需要使用此命令來安裝 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 套件 (例如 請求或 boto3):

    pip install -r requirements.txt -t python/

    有些 Python 套件,例如 NumPy 和 Pandas,包括編譯的 C 元件。如果您要在 macOS 或 Windows 上使用這些套件建置 layer,您可能需要使用此命令來安裝 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 就可以尋找和匯入套件。

使用您自己的程式碼建立 layer
  1. 為您的 layer 建立所需的頂層目錄:

    mkdir python
  2. python目錄中建立您的 Python 模組。下列範例模組透過確認訂單包含必要資訊來驗證訂單。

    範例 自訂模組:https://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 中建立 layer

您可以使用 AWS CLI 或 Lambda 主控台發佈 layer。

AWS CLI

執行 publish-layer-version AWS CLI 命令來建立 Lambda layer:

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

相容的執行時間參數是選用的。指定時,Lambda 會使用此參數來篩選 Lambda 主控台中的圖層。

Console
建立圖層 (主控台)
  1. 開啟 Lambda 主控台中的 層頁面

  2. 選擇 建立圖層

  3. 選擇上傳 .zip 檔案,然後上傳您先前建立的 .zip 封存檔。

  4. (選用) 針對相容的執行時間,選擇與您用來建置 layer 的 Python 版本對應的 Python 執行時間。

  5. 選擇建立

將 layer 新增至函數

AWS CLI

若要將 layer 連接至函數,請執行 update-function-configuration AWS CLI 命令。對於 --layers 參數,請使用 layer 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. 開啟 Lambda 主控台中的函數頁面

  2. 選擇 函數。

  3. 向下捲動至區段,然後選擇新增層

  4. 選擇圖層下,選取自訂圖層,然後選擇您的圖層。

    注意

    如果您在建立 layer 時未新增相容的執行時間,您的 layer 將不會列在此處。您可以改為指定 layer ARN。

  5. 選擇新增

範例應用程式

如需如何使用 Lambda 層的更多範例,請參閱《 AWS Lambda 開發人員指南 GitHub 儲存庫》中的 layer-python 範例應用程式。此應用程式包含兩個包含 Python 程式庫的層。建立圖層後,您可以部署和叫用對應的 函數,以確認圖層如預期般運作。