針對 Python Lambda 函數使用層
使用 Lambda 層封裝要在多個函式之間重複使用的程式碼與相依項。層通常具備程式庫相依性、自訂執行期或組態檔案。建立層包含三個一般步驟:
-
封裝層內容。這表示建立 .zip 封存檔,其中包含您要在函數中使用的相依項。
-
在 Lambda 中建立層。
-
將層新增至函數中。
封裝層內容
若要建立層,請將套件封裝成符合以下要求的 .zip 壓縮檔:
-
使用計劃用於 Lambda 函式的相同 Python 版本來建置層。例如,若透過 Python 3.13 建置層,需使用適用於函式的 Python 3.13 執行時期。
-
.zip 檔案必須在根層級包含
python目錄。 -
層中的套件必須與 Linux 相容。Lambda 函式會在 Amazon Linux 上執行。
您可以建立包含透過 pip 安裝的第三方 Python 程式庫 (例如 requests 或 pandas) 的層,或您自訂的 Python 模組與套件的層。
使用 pip 套件建立層
-
選擇下列其中一種方法,將
pip套件安裝到所需的頂層目錄 (python/): -
壓縮
python目錄的內容。.zip 檔案的目錄結構應如下所示:
python/# Required top-level directory └── requests/ └── boto3/ └── numpy/ └── (dependencies of the other packages)注意
如果使用 Python 虛擬環境 (venv) 來安裝套件,目錄結構將會有所不同 (例如
python/lib/python3.)。只要 .zip 檔案在根層級包含x/site-packagespython目錄,Lambda 就能順利找到並匯入套件。
使用自訂的程式碼建立層
-
為層建立所需的頂層目錄:
mkdir python -
在
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) } -
壓縮
python目錄的內容。.zip 檔案的目錄結構應如下所示:
python/# Required top-level directory └── validator.py -
在函式中,如同使用任何 Python 套件一樣,匯入並使用模組。範例:
from validator import validate_order, format_responseimport 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 主控台來發布層。
將層新增至函式
應用程式範例
如需如何使用 Lambda 層的更多範例,請參閱 AWS Lambda Developer Guide GitHub repository 中的 layer-python