【发布时间】:2021-01-20 04:25:28
【问题描述】:
我在 lambda 下面有 python 脚本,但在测试时遇到错误。
import json
import boto3
import os
from XXXXXXX import get_client
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)
def lambda_handler(event, context):
client = boto3.client("cloudwatch")
response = client.get_metric_statistics(
Namespace="AWS/Lambda",
MetricName="Errors",
Dimensions=[{"Name": "FunctionName", "Value": "XXXXXXX"}],
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", numalign="left", stralign="left"
)
print(message4)
error_list = []
for message2 in message3:
temp = {}
if message2["Sum"] > 0:
temp['There are some errors on QOS Invocations']
else:
temp['There are no errors on QOS Invocations']
error_list.append(temp)
return error_list
try:
error_list = Final_Sum(message2, message3)
error_list_final = json.dumps(error_list, indent=4, sort_keys=False)
print(error_list_final)
except Exception as ex:
print(ex)
pass
以下是遇到的错误。我已经尝试为 error_list 创建单独的函数,但遇到“'QOS 调用没有错误'”相同的错误。
{
"errorMessage": "'There are no errors on QOS Invocations'",
"errorType": "KeyError",
"stackTrace": [
" File \"/var/task/python/m3ce-getqosAPIerror.py\", line 53, in lambda_handler\n temp['There are no errors on QOS Invocations']\n"
]
}
这在本地运行时(在 lamdba 之外)运行良好,预期输出为:
+---------------------------+-------+--------+
| Timestamp | Sum | Unit |
|---------------------------+-------+--------|
| 2021-01-20T03:49:00+00:00 | 0 | Count |
| 2021-01-20T03:48:00+00:00 | 0 | Count |
| 2021-01-20T03:52:00+00:00 | 0 | Count |
| 2021-01-20T03:51:00+00:00 | 0 | Count |
| 2021-01-20T03:47:00+00:00 | 0 | Count |
| 2021-01-20T03:50:00+00:00 | 0 | Count |
+---------------------------+-------+--------+
'There are no errors on QOS Invocations'
【问题讨论】:
-
temp应该是什么?它被初始化为dict,但语法['There are...']试图检索 值,而不是set 值。简而言之,代码错误地将这些消息视为字典的键。我认为您打算将这些消息直接附加到error_list,所以就这样做吧。除此之外,我无法解释为什么它在本地有效 - 一定有一些差异在问题中没有考虑。
标签: python-3.x lambda conditional-statements keyerror