自动化报告系统
发布: (2025年12月31日 GMT+8 23:49)
4 分钟阅读
原文: Dev.to
Source: Dev.to
请提供您希望翻译的具体文本内容,我将按照要求将其翻译成简体中文并保留原始的格式、Markdown 语法以及技术术语。谢谢!
概览
- 使用 AWS Lambda 和其他无服务器工具实现每日报告自动化。
- 系统将会:
- 从多个来源收集数据。
- 生成 PDF 报告。
- 通过电子邮件发送报告。
- 每天触发此过程。
本指南假设您对 AWS 有基本了解。
第一步:创建 S3 存储桶
- 前往 S3 服务。
- 点击 Create bucket。
- 为存储桶命名(例如
daily-reports-s3-bucket)。 - 其余设置保持默认,点击 Create。
该存储桶将在需要时存储报告。
第2步:在 SES 中验证电子邮件地址
- 打开 Amazon SES。
- 在 Identity Management 下导航至 Email Addresses。
- 点击 Verify a New Email Address 并输入您的电子邮件。
- 检查收件箱并点击验证链接。
验证后,SES 可使用此地址发送电子邮件。
第3步:编写 Lambda 函数
- 前往 AWS Lambda 并点击 Create function。
- 选择 Author from scratch。
- 函数名称:
daily-report-lambda - 运行时: Python 3.9(或更高)
- 函数名称:
- 点击 Create function。
Lambda 函数代码
将默认代码替换为以下内容:
import boto3
from fpdf import FPDF
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def lambda_handler(event, context):
try:
# Generate the PDF report
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt="Daily Report", ln=True, align="C")
pdf.cell(200, 10, txt="This is your automated report.", ln=True)
# Save the PDF
report_path = "/tmp/daily_report.pdf"
pdf.output(report_path)
# Upload to S3 (Optional)
s3 = boto3.client('s3')
bucket_name = "daily-reports-s3-bucket"
s3.upload_file(report_path, bucket_name, "daily_report.pdf")
# Send email via SES with attachment using raw email
ses = boto3.client('ses')
msg = MIMEMultipart()
msg['From'] = "sender_email@gmail.com" # Replace with your SES‑verified email
msg['To'] = "receiver_email@gmail.com" # Replace with recipient email
msg['Subject'] = "Daily Report"
# Attach the text body
body = MIMEText("Please find the attached report.", 'plain')
msg.attach(body)
# Attach the PDF report
with open(report_path, 'rb') as file:
part = MIMEBase('application', 'octet-stream')
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
f'attachment; filename={os.path.basename(report_path)}')
msg.attach(part)
# Send the email using SES's send_raw_email
response = ses.send_raw_email(
Source=msg['From'],
Destinations=[msg['To']],
RawMessage={'Data': msg.as_string()}
)
return {"status": "success", "response": response}
except Exception as e:
return {"status": "error", "message": str(e)}
第4步:本地安装库并部署(可选)
Lambda 运行时不包含 fpdf,因此需要自行打包:
pip install fpdf -t ./package
cd package
zip -r ../lambda_layer.zip .
将生成的 ZIP(lambda_layer.zip)上传到你的 Lambda 函数,作为层或直接作为函数代码。
Step 5: Set Up EventBridge Trigger
- 打开 EventBridge。
- 点击 Create rule。
- Name:
daily-report-trigger - Define pattern: Schedule
- Cron expression:
cron(0 9 * * ? *)(每天 09:00 UTC)
- Name:
- 在 Target 下,选择你的 Lambda 函数 (
daily-report-lambda)。 - 点击 Create。
第6步:测试 Lambda 函数
- 在 Lambda 控制台,转到 Test 选项卡。
- 创建一个新的测试事件(可以保持默认模板为空)。
- 点击 Test。
检查收件箱,查看生成的 PDF 报告。
你已经构建了一个无服务器报告系统! 🎉
Happy Cloud Learning
— Adeel Abbas