Python 格式化 AWS lambda 请求时出错

Python error formatting an AWS lambda request

我必须使用 boto3 调用 AWS lambda。 我愿意:

client = boto3.client("lambda")

dtime1 = str(datetime.datetime.now())
#After some computations
dtime2 = str(datetime.datetime.now())

elapsed =  time.time() - start_time

payload = {"key_id":"1",
        "data_start":dtime1,
        "data_stop":dtime2,
        "elapsed_t": int(elapsed)}

r = client.invoke(
            FunctionName='mylambda',
            InvocationType='RequestResponse',
            Payload=bytes(str(payload), 'utf-8')
        )

print(r.read())

但是当我 运行 时发生错误:

"An error occurred (InvalidRequestContentException) when calling the Invoke operation: Could not parse request body into json: Unexpected character (''' (code 39)): was expecting double-quote to start field name\n at [Source: [B@4cb02e4e; line: 1, column: 3]"

我该如何解决我的问题?

提前致谢

如果要将 JSON 对象作为字符串传递,可以使用 json.dumps(payload),如 https://docs.python.org/3/library/json.html 中所述。

我看到的所有关于在 Lambda 调用中传递负载的官方文档都已丢失或不正确。这对我有用:

# Construct a dict object
payload = {"key": "value"}

# Invoke the Lambda function, passing the payload
lambda_client.invoke(FunctionName='myFunctionName',
                     InvocationType='RequestResponse',
                     Payload=json.dumps(payload))