aws-lambda-python-integration by giuseppe-trisciuoglio/developer-kit
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill aws-lambda-python-integration使用优化的冷启动和清晰架构创建高性能 AWS Lambda 函数的模式。
此技能提供了 AWS Lambda Python 开发的完整模式,涵盖两种主要方法:
两种方法都支持 API Gateway 和 ALB 集成,并具备生产就绪的配置。
在以下情况下使用此技能:
| 方法 | 冷启动 | 最适合 | 复杂度 |
|---|---|---|---|
| AWS Chalice | < 200ms | REST API、快速开发、内置路由 | 低 |
| 原始 Python | < 100ms | 简单的处理器、最大控制力、最小依赖 | 低 |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
my-chalice-app/
├── app.py # 包含路由的主应用程序
├── requirements.txt # 依赖项
├── .chalice/
│ ├── config.json # Chalice 配置
│ └── deploy/ # 部署产物
├── chalicelib/ # 附加模块
│ ├── __init__.py
│ └── services.py
└── tests/
└── test_app.py
my-lambda-function/
├── lambda_function.py # 处理器入口点
├── requirements.txt # 依赖项
├── template.yaml # SAM/CloudFormation 模板
└── src/ # 附加模块
├── __init__.py
├── handlers.py
└── utils.py
详细实现指南请参阅参考资料部分。快速示例:
AWS Chalice:
from chalice import Chalice
app = Chalice(app_name='my-api')
@app.route('/')
def index():
return {'message': 'Hello from Chalice!'}
原始 Python:
def lambda_handler(event, context):
return {
'statusCode': 200,
'body': json.dumps({'message': 'Hello from Lambda!'})
}
Python 具有出色的冷启动性能。关键策略:
详细模式请参阅 原始 Python Lambda。
在模块级别创建客户端并重用:
_dynamodb = None
def get_table():
global _dynamodb
if _dynamodb is None:
_dynamodb = boto3.resource('dynamodb').Table('my-table')
return _dynamodb
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")
保持 requirements.txt 最小化:
# 核心 AWS SDK - 始终需要
boto3>=1.35.0
# 只添加您需要的
requests>=2.32.0 # 如果调用外部 API
pydantic>=2.5.0 # 如果使用数据验证
返回带有请求 ID 的正确 HTTP 状态码:
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。
为 CloudWatch Insights 使用结构化日志:
import logging, json
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# 结构化日志
logger.info(json.dumps({
'eventType': 'REQUEST',
'requestId': context.aws_request_id,
'path': event.get('path')
}))
高级模式请参阅 原始 Python Lambda。
Serverless Framework:
# serverless.yml
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:
# 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 # 或 python3.11
Events:
ApiEvent:
Type: Api
Properties:
Path: /{proxy+}
Method: ANY
AWS Chalice:
chalice new-project my-api
cd my-api
chalice deploy --stage dev
完整的部署配置,包括 CI/CD、环境特定设置和高级 SAM/Serverless 模式,请参阅 Serverless 部署。
requirements.txt 最小化;对共享依赖项使用 Lambda 层context.get_remaining_time_in_millis() 来感知超时特定主题的详细指导:
输入:
Create a Python Lambda REST API using AWS Chalice for a todo application
过程:
chalice new-project 初始化 Chalice 项目chalice deploy 部署输出:
输入:
My Python Lambda has slow cold start, how do I optimize it?
过程:
输出:
输入:
Configure CI/CD for Python Lambda with SAM
过程:
输出:
.github/workflows/deploy.yml版本: 1.0.0
每周安装数
212
仓库
GitHub 星标数
174
首次出现
2026年2月20日
安全审计
安装于
codex190
gemini-cli188
github-copilot185
cursor183
opencode183
kimi-cli182
Patterns for creating high-performance AWS Lambda functions in Python with optimized cold starts and clean architecture.
This skill provides complete patterns for AWS Lambda Python development, covering two main approaches:
Both approaches support API Gateway and ALB integration with production-ready configurations.
Use this skill when:
| 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 |
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-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
See the References section for detailed implementation guides. Quick examples:
AWS Chalice:
from chalice import Chalice
app = Chalice(app_name='my-api')
@app.route('/')
def index():
return {'message': 'Hello from Chalice!'}
Raw Python:
def lambda_handler(event, context):
return {
'statusCode': 200,
'body': json.dumps({'message': 'Hello from Lambda!'})
}
Python has excellent cold start performance. Key strategies:
See Raw Python Lambda for detailed patterns.
Create clients at module level and reuse:
_dynamodb = None
def get_table():
global _dynamodb
if _dynamodb is None:
_dynamodb = boto3.resource('dynamodb').Table('my-table')
return _dynamodb
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")
Keep requirements.txt minimal:
# Core AWS SDK - always needed
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
Return proper HTTP codes with request ID:
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.
Use structured logging for CloudWatch Insights:
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 for advanced patterns.
Serverless Framework:
# 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:
# 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:
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.
requirements.txt minimal; use Lambda Layers for shared dependenciescontext.get_remaining_time_in_millis() for timeout awarenessFor detailed guidance on specific topics:
Input:
Create a Python Lambda REST API using AWS Chalice for a todo application
Process:
chalice new-projectchalice deployOutput:
Input:
My Python Lambda has slow cold start, how do I optimize it?
Process:
Output:
Input:
Configure CI/CD for Python Lambda with SAM
Process:
Output:
.github/workflows/deploy.ymlVersion: 1.0.0
Weekly Installs
212
Repository
GitHub Stars
174
First Seen
Feb 20, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex190
gemini-cli188
github-copilot185
cursor183
opencode183
kimi-cli182
agent-browser 浏览器自动化工具 - Vercel Labs 命令行网页操作与测试
147,400 周安装