Reputation: 27
Here's my app.py:
from flask import Flask
app = Flask(__name__)
@app.route('/', methods=['GET'])
def test_backend():
return "This is the test function for backend without lambda"
if __name__ == '__main__':
app.run(debug=True)
and lambda_handler in event_lambda.py:
def lambda_handler(event=None, context=None):
""" This lambda triggers other supporting functions """
return "This lambda handler triggers other functions "
I've tried to invoke lambda function through the following event in zappa_settings.json
"events": [{
"function": "backend.event_lambda.lambda_handler",
"expression": "cron(0 9 1 * ? *)"
}],
But it only returns "This is the test function for backend without lambda" from the app.py. The lambda function is invoked only when I invoke it manually using the command:
zappa invoke backend.event_lambda.lambda_handler
How can I set zappa to invoke the lambda function directly?
Upvotes: 2
Views: 1740
Reputation: 121
Im not sure if this is exactly what you are looking for, but this response https://stackoverflow.com/a/62119981 was a godsend for me while I was trying to invoke a function that was within zipped API deployed via Zappa on AWS Lambda.
Relevant fragment in source code: https://github.com/zappa/Zappa/blob/fff5ed8ad2ee071896a94133909adf220a8e47d9/zappa/handler.py#L380
TL;DR: use command
keyword in payload of what is send to lambda_handler to invoke any function in your API.
so, if you would like to invoke your lambda_handler
function which is part of an zipped API deployed on Lambda, you can do it via boto3:
from json import dumps
import boto3
lambda_client = boto3.Session().client(
service_name='lambda',
region_name='eu-central-1' # or other region
)
response = lambda_client.invoke(
FunctionName=<lambda_arn>,
Payload=dumps(
{
"command": "xxx_backend.event_lambda.lambda_handler", # xxx is the blacked out fragment of the name
}
)
)
And in response, apart from some Metadata, you should receive desired ("This lambda handler triggers other functions ") output.
It's also possible to pass some data into handler, BUT im not sure if there is any recommended keyword, so you can use any (beside those which are reserved!). Im using 'data'.
So, we will change your lambda_handler
function a little bit:
def lambda_handler(event=None, context=None):
""" This lambda triggers other supporting functions """
return f"This lambda handler received this payload: {event["data"]}"
The invokation has to change too:
from json import dumps
import boto3
lambda_client = boto3.Session().client(
service_name='lambda',
region_name='eu-central-1' # or other region
)
response = lambda_client.invoke(
FunctionName=<lambda_arn>,
Payload=dumps(
{
"command": "xxx_backend.event_lambda.lambda_handler", # xxx is the blacked out fragment of the name
"data": "Hello from Lambda!"
}
)
)
And the response from the invokation should look like this now:
This lambda handler received this payload: Hello from Lambda!"
Hope this helps.
Upvotes: 3