gpt4 book ai didi

python - 在 Python 上使用 describe_alarms 从 AWS 返回所有警报而不是仅返回 50 个

转载 作者:太空狗 更新时间:2023-10-30 02:29:07 24 4
gpt4 key购买 nike

在使用 describe_alarms 函数时,如何打印所有警报名称,而不是仅打印 50 个?

代码,使用 Python:

conn = boto.connect_cloudwatch()
alarms = conn.describe_alarms()
for item in alarms:
print item.name

谢谢。

最佳答案

虽然我来晚了一点,但这是我的解决方案(用 Java)。您必须获取下一个 token 并在循环中不断询问结果,直到没有下一个 token 为止,因此它的行为类似于网站上的分页

String nextToken = null;
List<MetricAlarm> metricAlarms = new ArrayList<>();
for (int i = 0; i < 100; i++) {

DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest();
describeAlarmsRequest.setNextToken(nextToken);
describeAlarmsRequest.setMaxRecords(100);

DescribeAlarmsResult describeAlarmsResult = getClient().describeAlarms(describeAlarmsRequest);
List<MetricAlarm> metricAlarmsTmp = describeAlarmsResult.getMetricAlarms();
metricAlarms.addAll(metricAlarmsTmp);
nextToken = describeAlarmsResult.getNextToken();
logger.info("nextToken: {}", nextToken);

if (nextToken == null) {
break;
}
}
logger.info("metricAlarms size: {}", metricAlarms.size());

当然还有改进的余地,例如创建 while 循环而不是 for 循环。

更新:

这是我的精修版

String nextToken = null;
List<MetricAlarm> metricAlarms = new ArrayList<>();

while (nextToken != null || metricAlarms.size() == 0) {
DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest().withNextToken(nextToken).withMaxRecords(100); // create the request
DescribeAlarmsResult describeAlarmsResult = getClient().describeAlarms(describeAlarmsRequest); // get the result
metricAlarms.addAll(describeAlarmsResult.getMetricAlarms()); // add new alarms to our list
nextToken = describeAlarmsResult.getNextToken(); // check if we have a nextToken
if (nextToken == null && cachedMetricAlarms.size() == 0) { // if we have no alarm in AWS we get inside the loop but we would never exit -> intercept that
break;
}
}
logger.info("metricAlarms size: {}", metricAlarms.size());

关于python - 在 Python 上使用 describe_alarms 从 AWS 返回所有警报而不是仅返回 50 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34179570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com