AWS Lambda Python:将MediaInfo部分响应推送至SNS技术咨询
Hey there! Sounds like you’ve already built a solid foundation with your AWS pipeline—nice work getting the S3→Lambda→MediaInfo→DynamoDB flow up and running. Pushing selected MediaInfo data to SNS is totally straightforward, and here’s a step-by-step implementation plan tailored to your setup:
First, create an SNS topic (standard or FIFO, depending on whether you need ordered messages) via the AWS Console or CLI. Then, ensure your Lambda execution role has permission to publish to this topic—stick to a narrow policy instead of broad access:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "sns:Publish", "Resource": "arn:aws:sns:YOUR_REGION:YOUR_ACCOUNT_ID:YOUR_MEDIA_TOPIC_NAME" } ] }
Since you’re getting XML from MediaInfo, you’ll need to extract the specific fields you want to send to SNS. For Python (the most common Lambda runtime), use the built-in xml.etree.ElementTree module to parse the response. Here’s an example of pulling key video metadata:
import xml.etree.ElementTree as ET # Assume 'mediainfo_xml' is the raw XML string from your MediaInfo CLI call root = ET.fromstring(mediainfo_xml) # Extract video track details (adjust fields based on what you care about) video_track = root.find(".//track[@type='Video']") if video_track: selected_metadata = { "file_name": event['Records'][0]['s3']['object']['key'], "resolution": f"{video_track.find('Width').text}x{video_track.find('Height').text}", "duration_sec": video_track.find('Duration').text.split('.')[0], "codec": video_track.find('CodecName').text, "file_size_mb": round(int(event['Records'][0]['s3']['object']['size']) / (1024 * 1024), 2) }
Add the SNS publish logic to your existing Lambda code. Use the AWS SDK (boto3 for Python) to send your formatted metadata. Choose between plain text or JSON messages—JSON is better for structured data consumed by other services:
import boto3 import json # Initialize SNS client outside the handler for better performance (reuses connections) sns_client = boto3.client('sns') SNS_TOPIC_ARN = "arn:aws:sns:YOUR_REGION:YOUR_ACCOUNT_ID:YOUR_MEDIA_TOPIC_NAME" def lambda_handler(event, context): # ... your existing code to run MediaInfo and retrieve XML output ... # ... parse XML into selected_metadata as shown above ... # Format the message (customize this to fit your subscriber needs) sns_message = f"New media file processed:\n\n{json.dumps(selected_metadata, indent=2)}" # Publish to SNS with error handling try: publish_response = sns_client.publish( TopicArn=SNS_TOPIC_ARN, Message=sns_message, Subject="Media File Metadata Update" ) print(f"Successfully sent SNS notification: {publish_response['MessageId']}") except Exception as e: print(f"Failed to publish to SNS: {str(e)}") # Optionally re-raise to trigger Lambda retries, or handle gracefully based on your needs raise e # ... your existing code to write metadata to DynamoDB ... return { 'statusCode': 200, 'body': 'Media processed and notification sent successfully' }
- Error Handling: Wrap the SNS publish call in a try-except block to avoid failing the entire Lambda execution if SNS is temporarily unavailable. You can also configure Lambda retries or dead-letter queues for persistent failures.
- Message Format: If your subscribers are other AWS services (like another Lambda or SQS), use JSON for easier parsing. For email/SMS subscribers, stick to plain text for readability.
- Performance: Initializing the
boto3client outside thelambda_handlerfunction reuses connections across invocations, reducing latency.
内容的提问来源于stack exchange,提问作者Richard Clarke

