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

标签 python amazon-web-services function aws-lambda python-requests

我正在创建我的(第一个)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/

相关文章:

amazon-web-services - 我可以在带有 vagrant 的 aws 上使用哪个 centos 图像?

c++ - 为什么一个常量函数返回的volatile类型可以是常量?

python - 读取 Python 请求到文件

python - 检查列表内字典之间的差异

android - Proguard 使用适用于 Android 的 AWS SDK 给出错误

javascript - for 循环仅适用于最后一项

php - 添加功能不适用于数据库

python - MapBox 使用的标准 GPS 纬度/经度/缩放坐标

java - 如何从 python 脚本设置系统属性以在 Java 代码中使用它?

python - 使用 boto 时,长时间运行的客户端对象是否安全?