aws-lambda-python-integration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAWS 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:
- AWS Chalice Framework - Full-featured framework with built-in routing, dependency injection, and local testing server
- 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开发的完整模式,涵盖两种主要方案:
- AWS Chalice框架 - 功能完备的框架,内置路由、依赖注入与本地测试服务器
- 原生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. 选择方案
| Approach | Cold Start | Best For | Complexity |
|---|---|---|---|
| AWS Chalice | < 200ms | REST APIs, rapid development, built-in routing | Low |
| Raw Python | < 100ms | Simple handlers, maximum control, minimal dependencies | Low |
| 方案 | 冷启动耗时 | 最佳适用场景 | 复杂度 |
|---|---|---|---|
| AWS Chalice | < 200ms | REST 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.pymy-chalice-app/
├── app.py # 主应用(含路由)
├── requirements.txt # 依赖包
├── .chalice/
│ ├── config.json # Chalice配置文件
│ └── deploy/ # 部署产物
├── chalicelib/ # 额外模块
│ ├── __init__.py
│ └── services.py
└── tests/
└── test_app.pyRaw 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.pymy-lambda-function/
├── lambda_function.py # 处理器入口
├── requirements.txt # 依赖包
├── template.yaml # SAM/CloudFormation模板
└── src/ # 额外模块
├── __init__.py
├── handlers.py
└── utils.py3. 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:
- Initialize at module level - Persists across warm invocations
- Use lazy loading - Defer heavy imports until needed
- Cache boto3 clients - Reuse connections between invocations
See Raw Python Lambda for detailed patterns.
Python的冷启动性能表现优异。核心优化策略:
- 模块级别初始化 - 初始化内容可在暖调用间持久化
- 使用延迟加载 - 仅在需要时导入重型依赖
- 缓存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 _dynamodbEnvironment 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 minimal:
requirements.txttxt
undefined保持精简:
requirements.txttxt
undefinedCore 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
undefinedrequests>=2.32.0 # 若需调用外部API
pydantic>=2.5.0 # 若需数据验证
undefinedError 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
undefinedServerless Framework:
yaml
undefinedserverless.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:**
```yamlservice: 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:**
```yamltemplate.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 devFor 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 minimal; use Lambda Layers for shared dependencies
requirements.txt - Native dependencies: Must be compiled for Amazon Linux 2 (x86_64 or arm64)
- 冷启动:Python冷启动性能优异,但需避免在模块级别导入重型依赖
- 依赖:保持精简;使用Lambda Layers管理共享依赖
requirements.txt - 原生依赖:必须针对Amazon Linux 2(x86_64或arm64)编译
Common Pitfalls
常见陷阱
- Importing heavy libraries at module level - Defer to function level if not always needed
- Not handling Lambda context - Use for timeout awareness
context.get_remaining_time_in_millis() - Not validating input - Always validate and sanitize event data
- Printing sensitive data - Be careful with logs and CloudWatch
- 模块级别导入重型库 - 若非必需,延迟至函数级别导入
- 未处理Lambda上下文 - 使用监控剩余时间
context.get_remaining_time_in_millis() - 未验证输入 - 始终验证并清理事件数据
- 打印敏感数据 - 谨慎处理日志与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 applicationProcess:
- Initialize Chalice project with
chalice new-project - Configure routes for CRUD operations
- Set up DynamoDB integration
- Configure deployment stages
- 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流程:
- 使用初始化Chalice项目
chalice new-project - 配置CRUD操作路由
- 设置DynamoDB集成
- 配置部署阶段
- 使用部署
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:
- Analyze imports and initialization code
- Move heavy imports inside functions (lazy loading)
- Cache boto3 clients at module level
- Remove unnecessary dependencies
- 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?流程:
- 分析导入与初始化代码
- 将重型依赖移至函数内部(延迟加载)
- 在模块级别缓存boto3客户端
- 移除不必要的依赖
- 必要时使用预置并发
输出:
- 重构后的延迟加载代码
- 优化后冷启动耗时<100ms
- 依赖分析报告
Example 3: Deploy with GitHub Actions
示例3:使用GitHub Actions部署
Input:
Configure CI/CD for Python Lambda with SAMProcess:
- Create GitHub Actions workflow
- Set up Python environment and dependencies
- Run pytest with coverage
- Package with SAM
- 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流程:
- 创建GitHub Actions工作流
- 设置Python环境与依赖
- 运行pytest并生成覆盖率报告
- 使用SAM打包
- 部署至开发/生产环境
输出:
- 完整的配置
.github/workflows/deploy.yml - 多阶段流水线
- 集成测试自动化
Version
版本
Version: 1.0.0
版本:1.0.0