AWS新手求助:通过Lambda从DynamoDB提取MQTT数据并展示到网页
Hey Abdul, let's work through this together since you're new to AWS and setting up this MQTT/DynamoDB/Lambda pipeline. I'll break down the solution into actionable steps, fix your Lambda code, and show you how to get the decoded data onto a webpage.
1. Fix & Complete Your Python Lambda Code
First, I noticed a typo in your snippet: boto3.response('dynam... should be boto3.resource('dynamodb') (or client). Below is a full, working Lambda function that fetches data from DynamoDB, decodes the Base64 payload, and returns it in a web-friendly format:
import boto3 import json import base64 import os # Initialize DynamoDB resource dynamodb = boto3.resource('dynamodb') # Pull table name from environment variable (better than hardcoding!) table_name = os.environ.get('DYNAMODB_TABLE', 'your-actual-table-name') table = dynamodb.Table(table_name) def lambda_handler(event, context): try: # Scan the DynamoDB table (use Query instead if you need filtered results) scan_response = table.scan() raw_items = scan_response['Items'] # Decode Base64 data for each item processed_items = [] for item in raw_items: # Replace 'mqtt_payload' with your actual Base64 field name if 'mqtt_payload' in item: try: # Decode Base64 to UTF-8 string decoded_content = base64.b64decode(item['mqtt_payload']).decode('utf-8') item['decoded_data'] = decoded_content except Exception as decode_err: item['decoded_data'] = f"Decode failed: {str(decode_err)}" processed_items.append(item) # Return JSON with CORS headers (so your webpage can call it) return { 'statusCode': 200, 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' # Restrict to your domain in production! }, 'body': json.dumps(processed_items) } except Exception as e: return { 'statusCode': 500, 'body': json.dumps(f"Error fetching data: {str(e)}") }
2. Set Up Lambda Permissions
Make sure your Lambda execution role has:
dynamodb:Scanpermission (adddynamodb:Queryif you plan to filter results later)- Access to read environment variables (default is allowed, but double-check IAM policies)
3. Connect Lambda to Your Webpage (Use API Gateway)
Lambda functions can't be called directly from a browser—you need AWS API Gateway as a middleman:
- Create an HTTP API (simpler for beginners) in API Gateway
- Add a
GETroute, and integrate it with your Lambda function - Deploy the API to get a public endpoint URL
- Use this URL in your webpage to fetch data
Example Webpage Code (JavaScript)
Drop this into an HTML file to display the decoded data:
<!DOCTYPE html> <html> <head> <title>MQTT Data Dashboard</title> <style> .item-card { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 5px; } </style> </head> <body> <h1>Decoded MQTT Data from DynamoDB</h1> <div id="data-container"></div> <script> // Replace with your API Gateway endpoint URL const apiEndpoint = 'https://your-api-id.execute-api.your-region.amazonaws.com/prod/get-mqtt-data'; fetch(apiEndpoint) .then(res => res.json()) .then(data => { const container = document.getElementById('data-container'); if (data.length === 0) { container.innerHTML = "<p>No data found in DynamoDB.</p>"; return; } // Build HTML for each data item let html = ''; data.forEach((item, index) => { html += ` <div class="item-card"> <h3>Item #${index + 1}</h3> <p><strong>Original Base64:</strong> ${item.mqtt_payload}</p> <p><strong>Decoded Content:</strong> ${item.decoded_data}</p> </div> `; }); container.innerHTML = html; }) .catch(err => { document.getElementById('data-container').innerHTML = `<p>Failed to load data: ${err.message}</p>`; }); </script> </body> </html>
4. Quick Tips for Beginners
- Avoid Hardcoding: Use Lambda environment variables for table names instead of writing them directly in code
- Production Security: Replace
Access-Control-Allow-Origin: *with your actual webpage domain to prevent unauthorized access - Pagination: If your DynamoDB table has more than 1MB of data, add logic to handle
LastEvaluatedKeyfrom the scan response - Logging: Add
print()statements or use theloggingmodule in Lambda to debug issues easily
内容的提问来源于stack exchange,提问作者abdul kadhar

