AWS Lambda[ERROR]函数接受1个位置参数,但给出了2个位置参数

2024-10-08 20:16:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但是,在触发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)

Tags: lambda函数eventjsonurldataonrequest
2条回答

错误消息告诉您lambda_handler函数有两个位置参数,但函数定义为只接受一个

Lambda会自动为处理程序函数提供两个参数,因此需要定义函数以接受两个参数

您可以通过将函数定义更改为:

def lambda_handler(lightID, lambda_context):

您的处理函数应定义为:

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.

很可能您的event只包含代码所示的Light ID,但是最好调用它event以识别它是传递到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"]}))

相关问题 更多 >

    热门问题