我正在尝试在 Python 中设置 AWS Lambda 函数,该函数在 IOT 分析处理期间触发,并将两个连续的 POST 请求发送到外部 API(如果满足条件)。我无法直接导入“请求”包,因为它对于内联编辑来说太大了,所以我已经将我的 Python 脚本以及包上传到 zip 文件中,然后将其上传到 AWS。
运行 lambda 时,我在请求包文件上收到错误,我不太明白。我也不确定如何返回 API 响应,因为我的响应出现序列化错误。这是我的 lambda 代码:
import json
import os
import time
import requests
def lambda_handler(event,context):
headers = {
"authorization": "Basic XXXXXXXXX",
"content_type": "application/json"
} #API request header
url = "https://example.com/path" #API request URL
msgs = json.loads(json.dumps(event))
for msg in msgs:
deviceID = msg["deviceID"]
data = msg["data"]
if (condition over received message):
body1 = {
"paramAA": paramAA,
"paramB": [{
"paramBA": paramBA1,
"paramBB": paramBB
}]
}
response_1 = requests.post(url,headers=headers,data=body1) #First API request
time.sleep(600)
body2 = {
"paramAA": paramAA,
"paramB": [{
"paramBA": paramBA2,
"paramBB": paramBB,
}]
}
response_2 = requests.post(url,headers=headers,data=body2) #Second API request
else:
pass
else:
pass
return {
'statusCode': 200,
'url' : url,
'response_1.code' : response_1.status_code,
'response_1_msg' : response_1.text,
'response_2.code' : response_2.status_code,
'response_2_msg' : response_2.text
}
您知道如何解决这些错误吗?
如果我用“reponse_1 : json.dumps(response1)”更改返回,我会收到这些错误(无论是使用 zip 包还是 SDK):
{
"errorMessage": "Object of type Response is not JSON serializable",
"errorType": "TypeError",
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 56, in lambda_handler\n 'response_1' : json.dumps(response_1),\n",
" File \"/var/lang/lib/python3.8/json/__init__.py\", line 231, in dumps\n return _default_encoder.encode(obj)\n",
" File \"/var/lang/lib/python3.8/json/encoder.py\", line 199, in encode\n chunks = self.iterencode(o, _one_shot=True)\n",
" File \"/var/lang/lib/python3.8/json/encoder.py\", line 257, in iterencode\n return _iterencode(o, 0)\n",
" File \"/var/lang/lib/python3.8/json/encoder.py\", line 179, in default\n raise TypeError(f'Object of type {o.__class__.__name__} '\n"