首页 > 解决方案 > 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
        )  

也许我用标志错误地解决了这个问题。很感谢任何形式的帮助。

提前致谢

标签: pythondjangoemail

解决方案


我有一个解决方案。我在警报模型中添加了一个已处理字段,默认为 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()

推荐阅读