See also: AWS RDS with Python: A Comprehensive CRUD Tutorial
Exploring Python AWS Lambda Examples
Simple Lambda Function
def lambda_handler(event, context): return { 'statusCode': 200, 'body': 'Hello from Lambda!' }
Explanation:
lambda_handler: The main function that AWS Lambda calls when the function is triggered.
event: An event parameter containing information about the triggering event.
context: An object containing information about the execution context.
The function returns a dictionary with a status code and a message in the response body.
S3 Event Trigger
import json def lambda_handler(event, context): # Process S3 event for record in event['Records']: bucket = record['s3']['bucket']['name'] key = record['s3']['object']['key'] print(f'File {key} is added to {bucket}') return { 'statusCode': 200, 'body': json.dumps('S3 event processed successfully') }
Explanation:
The function processes S3 events triggered by new objects being added to the bucket.
It extracts information such as bucket name and object key from the event.
The function prints a message and returns a response indicating successful processing.
DynamoDB Stream Trigger
import json def lambda_handler(event, context): # Process DynamoDB stream event for record in event['Records']: if record['eventName'] == 'INSERT': new_item = record['dynamodb']['NewImage'] print(f'New item added: {json.dumps(new_item)}') return { 'statusCode': 200, 'body': json.dumps('DynamoDB stream event processed successfully') }
Explanation:
The function processes DynamoDB stream events triggered by item inserts.
It extracts information about the new item and prints a message.
The function returns a response indicating successful processing.
API Gateway Proxy Integration
import json def lambda_handler(event, context): # Handle API Gateway proxy integration request_body = json.loads(event['body']) response_body = {'message': f'Hello, {request_body["name"]}!'} return { 'statusCode': 200, 'body': json.dumps(response_body) }
Explanation:
The function handles API Gateway proxy integration, extracting data from the request body.
It constructs a response body based on the received data.
The function returns a response with a customized message.
Remember to set up the necessary permissions, configure triggers, and adapt the code to your specific use case before deploying these Lambda functions in AWS.