[英]AWS Serverless - Lambda that supports both HTTP and Cloudwatch schedule event
My functions section in serverless.yml
looks similar to: serverless.yml
中的函数部分类似于:
functions:
MyLambda:
handler: handler.sayHello
name: my-lambda-say-hello
events:
- http:
path: /myPpath
method: post
cors: true
- schedule:
name: my-schedule-event
description: 'bla bla'
rate: rate(10 minutes)
input:
body: '{"name": "John"}'
My handler.sayHello
lambda function looks like:我的
handler.sayHello
lambda function 看起来像:
import json
def sayHello(event, context):
#Works for HTTP
print(json.loads(event['body'])['name'])
#Works for Cloudwatch schedule event
print(event['body']['name']
So basically I have a lambda function that gets a name and prints it.所以基本上我有一个 lambda function 获取名称并打印它。
This Lambda is triggered either by an HTTP request (I send the data as JSON in body) or by scheduled Cloudwatch event.此 Lambda 由 HTTP 请求(我在正文中将数据发送为 JSON)或计划的 Cloudwatch 事件触发。
As you can see in my Lambda function, when I'm trying to extract the name
property when it comes from an HTTP request, I need to json.loads()
the event body object.正如您在我的 Lambda function 中看到的那样,当我尝试从 HTTP 请求中提取
name
属性时,我需要json.loads()
事件主体 object。
However, when it comes from a scheduled event, I don't need to json.loads()
it at all.但是,当它来自预定事件时,我根本不需要
json.loads()
它。
Is it possible to somehow make my Lambda support both of those events, without toggling the json.loads()
?是否有可能以某种方式让我的 Lambda 支持这两个事件,而不切换
json.loads()
?
Thanks!谢谢!
The event
payload of a Lambda function will vary depending on the invoking service. Lambda function 的
event
负载会因调用服务而异。 They are not the same across Cloudwatch, API Gateway, or other services like SNS, SQS, EventBridge, DynamoDB, S3 - and more.它们在 Cloudwatch、API 网关或 SNS、SQS、EventBridge、DynamoDB、S3 等其他服务中并不相同。
Instead, you'll need to add logic which can conditionally extract the name
(and other attributes) depending on the invoking service.相反,您需要添加可以根据调用服务有条件地提取
name
(和其他属性)的逻辑。
You can either wrap json.loads
in a try/except
block, or you could check if the event
contains a requestContext
key;您可以将
json.loads
包装在try/except
块中,或者您可以检查event
是否包含requestContext
键; which would indicate the function was triggered by an HTTP Request through API Gateway.这表明 function 是由 HTTP 请求通过 API 网关触发的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.