aws-lambda-python-integration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AWS Lambda Python Integration

AWS Lambda Python集成方案

Patterns for creating high-performance AWS Lambda functions in Python with optimized cold starts and clean architecture.
本方案提供创建高性能Python版AWS Lambda函数的模式,包含优化的冷启动机制与清晰的架构设计。

Overview

概述

This skill provides complete patterns for AWS Lambda Python development, covering two main approaches:
  1. AWS Chalice Framework - Full-featured framework with built-in routing, dependency injection, and local testing server
  2. Raw Python - Minimal overhead approach with maximum flexibility and control
Both approaches support API Gateway and ALB integration with production-ready configurations.
本技能提供AWS Lambda Python开发的完整模式,涵盖两种主要方案:
  1. AWS Chalice框架 - 功能完备的框架,内置路由、依赖注入与本地测试服务器
  2. 原生Python方案 - 开销最小化方案,具备最高灵活性与可控性
两种方案均支持API Gateway和ALB集成,并提供生产就绪的配置。

When to Use

适用场景

Use this skill when:
  • Creating new Lambda functions in Python
  • Migrating existing Python applications to Lambda
  • Optimizing cold start performance for Python Lambda
  • Choosing between framework-based and minimal Python approaches
  • Configuring API Gateway or ALB integration
  • Setting up deployment pipelines for Python Lambda
在以下场景中使用本技能:
  • 创建基于Python的新Lambda函数
  • 将现有Python应用迁移至Lambda
  • 优化Python Lambda的冷启动性能
  • 在基于框架与轻量Python方案间做选择
  • 配置API Gateway或ALB集成
  • 为Python Lambda设置部署流水线

Instructions

操作指南

1. Choose Your Approach

1. 选择方案

ApproachCold StartBest ForComplexity
AWS Chalice< 200msREST APIs, rapid development, built-in routingLow
Raw Python< 100msSimple handlers, maximum control, minimal dependenciesLow
方案冷启动耗时最佳适用场景复杂度
AWS Chalice< 200msREST API、快速开发、内置路由
原生Python< 100ms简单处理器、最高可控性、最小依赖

2. Project Structure

2. 项目结构

AWS Chalice Structure

AWS Chalice项目结构

my-chalice-app/
├── app.py                    # Main application with routes
├── requirements.txt          # Dependencies
├── .chalice/
│   ├── config.json          # Chalice configuration
│   └── deploy/              # Deployment artifacts
├── chalicelib/              # Additional modules
│   ├── __init__.py
│   └── services.py
└── tests/
    └── test_app.py
my-chalice-app/
├── app.py                    # 主应用(含路由)
├── requirements.txt          # 依赖包
├── .chalice/
│   ├── config.json          # Chalice配置文件
│   └── deploy/              # 部署产物
├── chalicelib/              # 额外模块
│   ├── __init__.py
│   └── services.py
└── tests/
    └── test_app.py

Raw Python Structure

原生Python项目结构

my-lambda-function/
├── lambda_function.py       # Handler entry point
├── requirements.txt         # Dependencies
├── template.yaml            # SAM/CloudFormation template
└── src/                     # Additional modules
    ├── __init__.py
    ├── handlers.py
    └── utils.py
my-lambda-function/
├── lambda_function.py       # 处理器入口
├── requirements.txt         # 依赖包
├── template.yaml            # SAM/CloudFormation模板
└── src/                     # 额外模块
    ├── __init__.py
    ├── handlers.py
    └── utils.py

3. Implementation Examples

3. 实现示例

See the References section for detailed implementation guides. Quick examples:
AWS Chalice:
python
from chalice import Chalice
app = Chalice(app_name='my-api')

@app.route('/')
def index():
    return {'message': 'Hello from Chalice!'}
Raw Python:
python
def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': json.dumps({'message': 'Hello from Lambda!'})
    }
详细实现指南请查看参考资料部分。以下是快速示例:
AWS Chalice示例:
python
from chalice import Chalice
app = Chalice(app_name='my-api')

@app.route('/')
def index():
    return {'message': 'Hello from Chalice!'}
原生Python示例:
python
def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': json.dumps({'message': 'Hello from Lambda!'})
    }

Core Concepts

核心概念

Cold Start Optimization

冷启动优化

Python has excellent cold start performance. Key strategies:
  1. Initialize at module level - Persists across warm invocations
  2. Use lazy loading - Defer heavy imports until needed
  3. Cache boto3 clients - Reuse connections between invocations
See Raw Python Lambda for detailed patterns.
Python的冷启动性能表现优异。核心优化策略:
  1. 模块级别初始化 - 初始化内容可在暖调用间持久化
  2. 使用延迟加载 - 仅在需要时导入重型依赖
  3. 缓存boto3客户端 - 在调用间复用连接
详细模式请查看原生Python Lambda

Connection Management

连接管理

Create clients at module level and reuse:
python
_dynamodb = None

def get_table():
    global _dynamodb
    if _dynamodb is None:
        _dynamodb = boto3.resource('dynamodb').Table('my-table')
    return _dynamodb
在模块级别创建客户端并复用:
python
_dynamodb = None

def get_table():
    global _dynamodb
    if _dynamodb is None:
        _dynamodb = boto3.resource('dynamodb').Table('my-table')
    return _dynamodb

Environment Configuration

环境配置

python
class Config:
    TABLE_NAME = os.environ.get('TABLE_NAME')
    DEBUG = os.environ.get('DEBUG', 'false').lower() == 'true'

    @classmethod
    def validate(cls):
        if not cls.TABLE_NAME:
            raise ValueError("TABLE_NAME required")
python
class Config:
    TABLE_NAME = os.environ.get('TABLE_NAME')
    DEBUG = os.environ.get('DEBUG', 'false').lower() == 'true'

    @classmethod
    def validate(cls):
        if not cls.TABLE_NAME:
            raise ValueError("TABLE_NAME required")

Best Practices

最佳实践

Memory and Timeout Configuration

内存与超时配置

  • Memory: Start with 256MB for simple handlers, 512MB for complex operations
  • Timeout: Set based on expected processing time
    • Simple handlers: 3-5 seconds
    • API with DB calls: 10-15 seconds
    • Data processing: 30-60 seconds
  • 内存:简单处理器从256MB开始,复杂操作使用512MB
  • 超时:根据预期处理时间设置
    • 简单处理器:3-5秒
    • 含数据库调用的API:10-15秒
    • 数据处理:30-60秒

Dependencies

依赖管理

Keep
requirements.txt
minimal:
txt
undefined
保持
requirements.txt
精简:
txt
undefined

Core AWS SDK - always needed

核心AWS SDK - 必备

boto3>=1.35.0
boto3>=1.35.0

Only add what you need

仅添加必要依赖

requests>=2.32.0 # If calling external APIs pydantic>=2.5.0 # If using data validation
undefined
requests>=2.32.0 # 若需调用外部API pydantic>=2.5.0 # 若需数据验证
undefined

Error Handling

错误处理

Return proper HTTP codes with request ID:
python
def lambda_handler(event, context):
    try:
        result = process_event(event)
        return {'statusCode': 200, 'body': json.dumps(result)}
    except ValueError as e:
        return {'statusCode': 400, 'body': json.dumps({'error': str(e)})}
    except Exception as e:
        print(f"Error: {str(e)}")  # Log to CloudWatch
        return {'statusCode': 500, 'body': json.dumps({'error': 'Internal error'})}
See Raw Python Lambda for structured error patterns.
返回标准HTTP状态码,并包含请求ID:
python
def lambda_handler(event, context):
    try:
        result = process_event(event)
        return {'statusCode': 200, 'body': json.dumps(result)}
    except ValueError as e:
        return {'statusCode': 400, 'body': json.dumps({'error': str(e)})}
    except Exception as e:
        print(f"Error: {str(e)}")  # 日志输出至CloudWatch
        return {'statusCode': 500, 'body': json.dumps({'error': 'Internal error'})}
结构化错误模式请查看原生Python Lambda

Logging

日志记录

Use structured logging for CloudWatch Insights:
python
import logging, json
logger = logging.getLogger()
logger.setLevel(logging.INFO)
使用结构化日志以适配CloudWatch Insights:
python
import logging, json
logger = logging.getLogger()
logger.setLevel(logging.INFO)

Structured log

结构化日志

logger.info(json.dumps({ 'eventType': 'REQUEST', 'requestId': context.aws_request_id, 'path': event.get('path') }))

See [Raw Python Lambda](references/raw-python-lambda.md#logging) for advanced patterns.
logger.info(json.dumps({ 'eventType': 'REQUEST', 'requestId': context.aws_request_id, 'path': event.get('path') }))

高级日志模式请查看[原生Python Lambda](references/raw-python-lambda.md#logging)。

Deployment Options

部署选项

Quick Start

快速开始

Serverless Framework:
yaml
undefined
Serverless Framework:
yaml
undefined

serverless.yml

serverless.yml

service: my-python-api provider: name: aws runtime: python3.12 # or python3.11 functions: api: handler: lambda_function.lambda_handler events: - http: path: /{proxy+} method: ANY

**AWS SAM:**
```yaml
service: my-python-api provider: name: aws runtime: python3.12 # 或python3.11 functions: api: handler: lambda_function.lambda_handler events: - http: path: /{proxy+} method: ANY

**AWS SAM:**
```yaml

template.yaml

template.yaml

AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31
Resources: ApiFunction: Type: AWS::Serverless::Function Properties: CodeUri: ./ Handler: lambda_function.lambda_handler Runtime: python3.12 # or python3.11 Events: ApiEvent: Type: Api Properties: Path: /{proxy+} Method: ANY

**AWS Chalice:**
```bash
chalice new-project my-api
cd my-api
chalice deploy --stage dev
For complete deployment configurations including CI/CD, environment-specific settings, and advanced SAM/Serverless patterns, see Serverless Deployment.
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31
Resources: ApiFunction: Type: AWS::Serverless::Function Properties: CodeUri: ./ Handler: lambda_function.lambda_handler Runtime: python3.12 # 或python3.11 Events: ApiEvent: Type: Api Properties: Path: /{proxy+} Method: ANY

**AWS Chalice:**
```bash
chalice new-project my-api
cd my-api
chalice deploy --stage dev
包含CI/CD、环境特定设置及高级SAM/Serverless模式的完整部署配置,请查看无服务器部署

Constraints and Warnings

约束与注意事项

Lambda Limits

Lambda限制

  • Deployment package: 250MB unzipped maximum (50MB zipped)
  • Memory: 128MB to 10GB
  • Timeout: 15 minutes maximum
  • Concurrent executions: 1000 default (adjustable)
  • Environment variables: 4KB total size
  • 部署包:最大250MB(未压缩),50MB(压缩后)
  • 内存:128MB至10GB
  • 超时:最大15分钟
  • 并发执行数:默认1000(可调整)
  • 环境变量:总大小4KB

Python-Specific Considerations

Python特定注意事项

  • Cold start: Python has excellent cold start performance, but avoid heavy imports at module level
  • Dependencies: Keep
    requirements.txt
    minimal; use Lambda Layers for shared dependencies
  • Native dependencies: Must be compiled for Amazon Linux 2 (x86_64 or arm64)
  • 冷启动:Python冷启动性能优异,但需避免在模块级别导入重型依赖
  • 依赖:保持
    requirements.txt
    精简;使用Lambda Layers管理共享依赖
  • 原生依赖:必须针对Amazon Linux 2(x86_64或arm64)编译

Common Pitfalls

常见陷阱

  1. Importing heavy libraries at module level - Defer to function level if not always needed
  2. Not handling Lambda context - Use
    context.get_remaining_time_in_millis()
    for timeout awareness
  3. Not validating input - Always validate and sanitize event data
  4. Printing sensitive data - Be careful with logs and CloudWatch
  1. 模块级别导入重型库 - 若非必需,延迟至函数级别导入
  2. 未处理Lambda上下文 - 使用
    context.get_remaining_time_in_millis()
    监控剩余时间
  3. 未验证输入 - 始终验证并清理事件数据
  4. 打印敏感数据 - 谨慎处理日志与CloudWatch内容

Security Considerations

安全注意事项

  • Never hardcode credentials; use IAM roles and environment variables
  • Validate all input data
  • Use least privilege IAM policies
  • Enable CloudTrail for audit logging
  • 切勿硬编码凭证;使用IAM角色与环境变量
  • 验证所有输入数据
  • 使用最小权限原则配置IAM策略
  • 启用CloudTrail以实现审计日志

References

参考资料

For detailed guidance on specific topics:
  • AWS Chalice - Complete Chalice setup, routing, middleware, deployment
  • Raw Python Lambda - Minimal handler patterns, module caching, packaging
  • Serverless Deployment - Serverless Framework, SAM, CI/CD pipelines
  • Testing Lambda - pytest, moto, SAM Local, localstack
特定主题的详细指南:
  • AWS Chalice - 完整Chalice设置、路由、中间件、部署指南
  • 原生Python Lambda - 轻量处理器模式、模块缓存、打包方案
  • 无服务器部署 - Serverless Framework、SAM、CI/CD流水线
  • Lambda测试 - pytest、moto、SAM Local、localstack

Examples

示例

Example 1: Create an AWS Chalice REST API

示例1:创建AWS Chalice REST API

Input:
Create a Python Lambda REST API using AWS Chalice for a todo application
Process:
  1. Initialize Chalice project with
    chalice new-project
  2. Configure routes for CRUD operations
  3. Set up DynamoDB integration
  4. Configure deployment stages
  5. Deploy with
    chalice deploy
Output:
  • Complete Chalice project structure
  • REST API with CRUD endpoints
  • DynamoDB table configuration
  • Deployment configuration
输入:
Create a Python Lambda REST API using AWS Chalice for a todo application
流程:
  1. 使用
    chalice new-project
    初始化Chalice项目
  2. 配置CRUD操作路由
  3. 设置DynamoDB集成
  4. 配置部署阶段
  5. 使用
    chalice deploy
    部署
输出:
  • 完整Chalice项目结构
  • 具备CRUD端点的REST API
  • DynamoDB表配置
  • 部署配置

Example 2: Optimize Cold Start for Raw Python

示例2:优化原生Python冷启动

Input:
My Python Lambda has slow cold start, how do I optimize it?
Process:
  1. Analyze imports and initialization code
  2. Move heavy imports inside functions (lazy loading)
  3. Cache boto3 clients at module level
  4. Remove unnecessary dependencies
  5. Use provisioned concurrency if needed
Output:
  • Refactored code with lazy loading
  • Optimized cold start < 100ms
  • Dependency analysis
输入:
My Python Lambda has slow cold start, how do I optimize it?
流程:
  1. 分析导入与初始化代码
  2. 将重型依赖移至函数内部(延迟加载)
  3. 在模块级别缓存boto3客户端
  4. 移除不必要的依赖
  5. 必要时使用预置并发
输出:
  • 重构后的延迟加载代码
  • 优化后冷启动耗时<100ms
  • 依赖分析报告

Example 3: Deploy with GitHub Actions

示例3:使用GitHub Actions部署

Input:
Configure CI/CD for Python Lambda with SAM
Process:
  1. Create GitHub Actions workflow
  2. Set up Python environment and dependencies
  3. Run pytest with coverage
  4. Package with SAM
  5. Deploy to dev/prod stages
Output:
  • Complete
    .github/workflows/deploy.yml
  • Multi-stage pipeline
  • Integrated test automation
输入:
Configure CI/CD for Python Lambda with SAM
流程:
  1. 创建GitHub Actions工作流
  2. 设置Python环境与依赖
  3. 运行pytest并生成覆盖率报告
  4. 使用SAM打包
  5. 部署至开发/生产环境
输出:
  • 完整的
    .github/workflows/deploy.yml
    配置
  • 多阶段流水线
  • 集成测试自动化

Version

版本

Version: 1.0.0
版本:1.0.0