You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用列表推导式遍历Flask-SQLAlchemy查询结果统计Critical告警

解决建议

1. 修复列表推导式的错误

你遇到的AttributeError是因为alert_data是.all()返回的列表对象,列表本身没有alertSevertiy属性,且你还拼写错了属性名(正确应为alertSeverity)。正确写法需遍历列表中的每个告警对象,再检查其alertSeverity字段:

total_crit_alerts = sum(1 for alert in alert_data if alert.alertSeverity == 'Critical')

2. 更高效的解决方案:让数据库直接统计

当前先拉取所有未修复告警再统计的方式,在数据量大时效率极低。最优做法是通过SQLAlchemy构造过滤查询,让数据库直接执行统计操作,仅返回结果:

total_crit_alerts = Alerts.query.filter_by(
    alertRemediated=False,
    alertSeverity='Critical'
).count()

若需更复杂的条件逻辑,可使用filter写法:

total_crit_alerts = Alerts.query.filter(
    Alerts.alertRemediated == False,
    Alerts.alertSeverity == 'Critical'
).count()

这种方式无需将所有告警数据加载到内存,数据库会执行COUNT原生查询,性能提升显著。

内容的提问来源于stack exchange,提问作者Bryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 16:11:16