python - Django仅在新警报上发送电子邮件警报
问题描述
我正在尝试为刚刚创建的所有新警报发送电子邮件警报。我努力了
last_alert = Alert.objects.filter(kiosk=kiosk).last()
但这只会得到最后一个警报,并且一直触发相同的警报。可以一次触发 3 个警报。我正在尝试实现一个标志以了解是否已发送警报。我可能在这里使用最新的错误。
last_alert = Alert.objects.filter(kiosk=kiosk).latest('pk')
if last_alert.created_on:
alert_status = HTTP_208_ALREADY_REPORTED
send_alert_email = False
else:
alert_status = HTTP_201_CREATED
send_alert_email = True
last_alert.created_on = datetime.now(last_alert.kiosk.location.timezone)
Alert.create(kiosk=kiosk, created_on=datetime.now(last_alert.kiosk.location.timezone))
last_alert.save()
# Get Timezone aware date and time
current_dt = datetime.now().astimezone(kiosk.location.timezone)
current_time = current_dt.strftime('%I:%M %p')
current_date = current_dt.strftime('%m/%d/%Y')
email_props2 = {
'method': 'EMAIL',
'email': 'john@example.com',
'data': {
'facility': last_alert.kiosk.location.name,
'description': last_alert.description,
'pk': last_alert.pk,
'time': current_time,
'date': current_date,
'kioskName': kiosk.name,
'alert_type_display': last_alert.alert_type_display
}
}
if send_alert_email:
_send_email(
[email_props2['email']],
{'data': email_props2['data']},
ALERT_TEMPLATE_ID
)
也许我用标志错误地解决了这个问题。很感谢任何形式的帮助。
提前致谢
解决方案
我有一个解决方案。我在警报模型中添加了一个已处理字段,默认为 False。然后过滤所有带有字段处理=假的警报。遍历所有警报,如果处理=假发送电子邮件,然后设置处理=真。
last_alert = Alert.objects.filter(kiosk=kiosk, processed=False)
# Get Timezone aware date and time
for alert in last_alert:
if alert.processed == False:
current_dt = datetime.now().astimezone(kiosk.location.timezone)
current_time = current_dt.strftime('%I:%M %p')
current_date = current_dt.strftime('%m/%d/%Y')
email_props2 = {
'method': 'EMAIL',
'email': 'john@example.com',
'data': {
'facility': alert.kiosk.location.name,
'description': alert.description,
'pk': alert.pk,
'time': current_time,
'date': current_date,
'kioskName': kiosk.name,
'alert_type_display': alert.alert_type_display
}
}
# Straight up send it, dude
_send_email(
[email_props2['email']],
{'data': email_props2['data']},
ALERT_TEMPLATE_ID
)
alert.processed = True
alert.save()
推荐阅读
- python - 在 Python 3.8 中将不同行上的字符打印成字符串
- azure - 微软 Azure 函数应用
- java - 链表多项式为什么我的输出只打印第一项
- python - 为什么我不能改变我的乌龟的宽度?
- pdf - GhostScript 可以生成 JPEG2000 压缩的 PDF 吗?
- python-3.x - 前端应用程序到后端服务器 websocket 连接可以有一个生产者
- javascript - 动态填充的 div 不可滚动
- r - 将列值转换为列名并保留所有值而不聚合,Id 具有重复值
- javascript - 尝试让两个滑块在页面中工作时发生冲突脚本
- python - 如何将`for line.split() in line:`作为列表理解