gpt4 book ai didi

python - AWS Lambda [错误]函数接受 1 个位置参数,但给出了 2 个

转载 作者:行者123 更新时间:2023-12-01 06:31:48 25 4
gpt4 key购买 nike

我正在创建我的(第一个)Lambda 函数。 Lambda 设计用于打开/关闭飞利浦 HUE 灯泡。 Lambda 函数的触发器是 AWS IoT (Dash) 按钮。

但是,在触发 Lambda 函数后,我收到以下错误消息:

[ERROR] TypeError: lambda_handler() takes 1 positional argument but 2 were given
Traceback (most recent call last):
File "/var/runtime/bootstrap.py", line 131, in handle_event_request
response = request_handler(event, lambda_context)

任何人都可以深入了解我的 Python 代码有什么问题吗?谢谢!

import requests,json

bridgeIP = "PublicIPAddress:999"
userID = "someone"
lightID = "2"

def lambda_handler(lightID):
url = "http://"+bridgeIP+"/api/"+userID+"/lights/"+lightID
r = requests.get(url)
data = json.loads(r.text)
if data["state"]["on"] == False:
r = requests.put(url+"/state",json.dumps({'on':True}))
elif data["state"]["on"] == True:
r = requests.put(url+"/state",json.dumps({'on':False}))

lambda_handler(lightID)

最佳答案

您的处理函数应定义为:

def lambda_handler(event, context):
lightID = event
...

来自AWS Lambda Function Handler in Python - AWS Lambda :

event – AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type.

When you invoke your function, you determine the content and structure of the event. When an AWS service invokes your function, the event structure varies by service.

context – AWS Lambda uses this parameter to provide runtime information to your handler.

您的事件很可能仅包含代码所示的Light ID,但最好将其称为事件以识别它是一个值被传递到 Lambda 函数,但您的代码随后选择将其解释为 lightID

此外,您的代码不应调用lambda_handler 函数。 AWS Lambda 服务将在调用该函数时执行此操作。

最后,您可能想利用 Python 3.x f-strings,它可以制作更漂亮的格式字符串:

import requests
import json

bridgeIP = "PublicIPAddress:999"
userID = "someone"

def lambda_handler(event, context):
lightID = event
url = f"http://{bridgeIP}/api/{userID}/lights/{lightID}"

r = requests.get(url)
data = json.loads(r.text)

r = requests.put(f"{url}/state", json.dumps({'on': not data["state"]["on"]}))

关于python - AWS Lambda [错误]函数接受 1 个位置参数,但给出了 2 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59870972/

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