Search code examples
python-3.xconditional-statementsamazon-cloudwatchtabulate

How to I get data from tabulated data then print a message


I have below output after tabulating response from cloudwatch using get_metric_statistics. I would like to add validation that if any Sum is greater than 0 it will print a message saying there is an error. And if all Sum is equal to zero it will say no error.

> +| Timestamp              |   Sum | Unit   | |
> 2021-01-12T09:31:00+00:00 |     0 | Count  | |
> 2021-01-12T09:30:00+00:00 |     0 | Count  | |
> 2021-01-12T09:33:00+00:00 |     0 | Count  | |
> 2021-01-12T09:29:00+00:00 |     0 | Count  | |
> 2021-01-12T09:32:00+00:00 |     0 | Count  | |
> 2021-01-12T09:28:00+00:00 |     0 | Count  |
> +---------------------------+-------+--------+

Below is my python script

import json
import boto3
import os
from datetime import datetime, timedelta
from tabulate import tabulate

client = boto3.client("lambda")


class DateTimeEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime):
            return o.isoformat()

        return json.JSONEncoder.default(self, o)


client = boto3.client("cloudwatch")
response = client.get_metric_statistics(
    Namespace="AWS/Lambda",
    MetricName="Errors",
    Dimensions=[{"Name": "FunctionName", "Value": "XXX"}],
    StartTime=datetime.utcnow() - timedelta(seconds=360),
    EndTime=datetime.utcnow(),
    Period=60,
    Statistics=["Sum"],
)

message = json.dumps(response, cls=DateTimeEncoder)
message2 = json.loads(message)
message3 = message2["Datapoints"]
message4 = tabulate(message3, headers="keys", tablefmt="psql")
print(message4)

I know this seems easy but please help. Thanks!


Solution

  • add something like:

    for message in message2:
       if message["Sum"] > 0:
          print("Some error occured")
       else:
          pass
    

    so if you don't get a feedback, there's no error. In case some Sum is greater 0, it'll tell you Some error