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

針對 Python Lambda 函數使用層

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

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

  2. 在 Lambda 中建立層。

  3. 將層新增至函數中。

封裝層內容

若要建立層,請將套件封裝成符合以下要求的 .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 目錄的內容。

    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 就能順利找到並匯入套件。

使用自訂的程式碼建立層
  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 目錄的內容。

    Linux/macOS
    zip -r layer.zip python/
    PowerShell
    Compress-Archive -Path .\python -DestinationPath .\layer.zip

    .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 中建立層

您可以使用 AWS CLI 或 Lambda 主控台來發布層。

AWS CLI

執行 publish-layer-version AWS 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 主控台中的 層頁面

  2. 選擇 建立圖層

  3. 選擇上傳 .zip 檔案,然後上傳先前建立的 .zip 壓縮檔。

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

  5. 選擇建立

將層新增至函式

AWS CLI

若要將層連接至函式,請執行 update-function-configuration AWS 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"

如果您使用 AWS CLI 第 2 版,則需要 cli-binary-format 選項。若要讓此成為預設的設定,請執行 aws configure set cli-binary-format raw-in-base64-out。若要取得更多資訊,請參閱《AWS Command Line Interface 使用者指南第 2 版》AWS CLI 支援的全域命令列選項

Console
將層新增至函式
  1. 開啟 Lambda 主控台中的函數頁面

  2. 選擇函式。

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

  4. 選擇層欄位中,選取自訂層,然後選擇要使用的層。

    注意

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

  5. 選擇新增

應用程式範例

如需如何使用 Lambda 層的更多範例,請參閱 AWS Lambda Developer Guide GitHub repository 中的 layer-python 範例應用程式。此應用程式包含兩個內含 Python 程式庫的層。建立層之後,您可以部署並調用對應的函式,驗證層是否如預期運作。