Synthèse automatique
Cette skill fournit des patrons d'intégration AWS Lambda en Python, avec optimisation des cold starts et choix entre AWS Chalice et un handler Python minimal.
Points forts
- Compare explicitement Chalice et le Python brut selon le cold start, le cas d'usage et la complexité
- Donne des structures de projet concrètes pour les deux approches (Chalice et SAM/CloudFormation)
- Inclut des patrons de réutilisation des clients boto3 et de configuration par variables d'environnement
- Couvre l'intégration API Gateway / ALB et les réglages mémoire et timeout
Limites
- Le contenu des guides détaillés est renvoyé vers des fichiers references/ qui ne sont pas inclus ici
- Ne traite pas du provisioned concurrency, des Lambda Layers ni des architectures container
- Les valeurs de mémoire et de timeout sont des points de départ génériques, à ajuster selon la charge réelle
À utiliser pour créer ou déployer une fonction Lambda Python, ou pour arbitrer entre Chalice et un handler minimal afin de réduire les cold starts.
À éviter si vous ciblez un autre runtime que Python ou un fournisseur serverless hors AWS, ou si vous cherchez des patrons avancés de concurrency et de layers non couverts ici.
Analyse de sécurité
PrudenceThe SKILL.md is purely educational documentation for AWS Lambda Python patterns. It contains no destructive commands, no curl|sh piping, no credential/secret exfiltration, and no obfuscated payloads. However, it declares Bash/Write/Edit and discusses deploying to AWS via SAM/Serverless/Chalice, so an agent using it could create or modify cloud resources with real cost/infra impact. Because the powerful tools are used for legitimate development purposes rather than clearly safe read-only content, caution is the appropriate rating.
- •Declares Bash/Write/Edit tools and discusses deployment to AWS, which can create billable resources and modify cloud infrastructure
- •Minor: includes build/deploy guidance (serverless print, sam validate) but no destructive commands, secret exfiltration, or obfuscated payloads present
Exemples
Create an AWS Lambda Python REST API with AWS Chalice: set up the project structure, add a /items GET route backed by DynamoDB, and show the .chalice/config.json for deployment.Write a minimal raw Python Lambda handler with API Gateway integration, cache the boto3 client at module level, and add a SAM template.yaml to deploy it.My Python Lambda has slow cold starts—review my handler imports and boto3 client setup and refactor it for lazy loading and connection reuse, then recommend memory and timeout values.name: aws-lambda-python-integration description: Provides AWS Lambda integration patterns for Python with cold start optimization. Use when deploying Python functions to AWS Lambda, choosing between AWS Chalice and raw Python approaches, optimizing cold starts, configuring API Gateway or ALB integration, or implementing serverless Python applications. Triggers include "create lambda python", "deploy python lambda", "chalice lambda aws", "python lambda cold start", "aws lambda python performance", "python serverless framework". allowed-tools: Read, Write, Edit, Bash, Glob, Grep
AWS Lambda Python Integration
Patterns for creating high-performance AWS Lambda functions in Python with optimized cold starts and clean architecture.
Overview
AWS Lambda Python integration with two approaches: AWS Chalice (full-featured framework) and Raw Python (minimal overhead). Both support API Gateway/ALB integration with production-ready configurations.
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
Instructions
1. Choose Your Approach
| 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 |
2. Project Structure
AWS Chalice Structure
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
Raw Python Structure
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
3. Implementation Examples
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!'})
}
Core Concepts
Cold Start Optimization
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.
Connection Management
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
Environment Configuration
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
Dependencies
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
Error Handling
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.
Logging
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.
Deployment Options
Quick Start
Validation Checkpoint: Always run
serverless printorsam validatebefore deploying to catch configuration errors early.
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 local 8080 # Test locally before deploying
chalice deploy --stage dev
Validation Checkpoint: Test locally with
chalice localorsam local invokebefore deploying to production.
For complete deployment configurations including CI/CD, environment-specific settings, and advanced SAM/Serverless patterns, see Serverless Deployment.
Constraints and Warnings
Lambda Limits
- 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
Python-Specific Considerations
- Cold start: Python has excellent cold start performance; avoid heavy imports at module level
- Dependencies: Keep
requirements.txtminimal; use Lambda Layers for shared dependencies - Native dependencies: Must be compiled for Amazon Linux 2 (x86_64 or arm64)
Common Pitfalls
- Importing heavy libraries at module level - Defer to function level if not always needed
- Not handling Lambda context - Use
context.get_remaining_time_in_millis()for timeout awareness - Not validating input - Always validate and sanitize event data
- Printing sensitive data - Be careful with logs and CloudWatch
Error Recovery: If deployment fails, check CloudWatch logs for initialization errors and run sam logs to diagnose issues.
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
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
Examples
Example 1: Create an AWS Chalice REST API
Input:
Create a Python Lambda REST API using AWS Chalice for a todo application
Process:
- 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
Example 2: Optimize Cold Start for Raw 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
Example 3: Deploy with GitHub Actions
Input:
Configure CI/CD for Python Lambda with SAM
Process:
- 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
Version
Version: 1.0.0
Du fichier au premier essai
Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.
Consulter la source et ses fichiers annexesCe téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.
1. Télécharger le fichier
Télécharger SKILL.mdDepuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/aws-lambda-python-integration-mrwakd28/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.
Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.
mkdir -p '.skill-downloads/aws-lambda-python-integration-mrwakd28' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/aws-lambda-python-integration-mrwakd28/download' --output '.skill-downloads/aws-lambda-python-integration-mrwakd28/SKILL.md.part' && mv '.skill-downloads/aws-lambda-python-integration-mrwakd28/SKILL.md.part' '.skill-downloads/aws-lambda-python-integration-mrwakd28/SKILL.md'2. Vérifier les prérequis
Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.
Outils déclarés par l’auteur (à vérifier dans votre agent) : Read, Write, Edit, Bash, Glob, Grep
Extrait original : Dependencies
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
Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.
3. Charger la skill
Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.
Claude Code
test -f '.skill-downloads/aws-lambda-python-integration-mrwakd28/SKILL.md' && test -s '.skill-downloads/aws-lambda-python-integration-mrwakd28/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/aws-lambda-python-integration' && cp -R '.skill-downloads/aws-lambda-python-integration-mrwakd28' '.claude/skills/aws-lambda-python-integration'Cursor
test -f '.skill-downloads/aws-lambda-python-integration-mrwakd28/SKILL.md' && test -s '.skill-downloads/aws-lambda-python-integration-mrwakd28/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/aws-lambda-python-integration' && cp -R '.skill-downloads/aws-lambda-python-integration-mrwakd28' '.cursor/skills/aws-lambda-python-integration'Codex
test -f '.skill-downloads/aws-lambda-python-integration-mrwakd28/SKILL.md' && test -s '.skill-downloads/aws-lambda-python-integration-mrwakd28/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/aws-lambda-python-integration' && cp -R '.skill-downloads/aws-lambda-python-integration-mrwakd28' '.agents/skills/aws-lambda-python-integration'OpenSkills
OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.
Installation officielle d’OpenSkillsopenskills install './.skill-downloads/aws-lambda-python-integration-mrwakd28'openskills read 'aws-lambda-python-integration-mrwakd28'La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.
Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.
openskills syncMode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.
4. Faire un premier essai
Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :
Lis .skill-downloads/aws-lambda-python-integration-mrwakd28/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.
Configurer un canal de discussion avec SecretRefs
DevOps
Configurez des canaux de discussion avec des commandes non interactives, les secrets étant uniquement des SecretRefs. Couvre les étapes de collecte, modification, réparation et vérification.
Enquêter sur les échecs CI de ClickHouse
DevOps
Investigue un échec CI de ClickHouse de bout en bout à partir d'une URL de PR ou de rapport S3. Récupère les tests échoués, classe flaky vs vraie régression, et cherche des issues/fixes existants.
Revue de PR Ansible
DevOps
Examine une PR Ansible selon le processus standardisé du projet, incluant la validation des changelogs, la couverture de tests et le suivi des commentaires.