本文介绍了AWS Lambda:使用boto3 invoke从另一个AWS lambda调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的lambda函数,位于以下端点下:

I have simple lambda function that is located under following endpoint:

https://******.execute-api.eu-west-2.amazonaws.com/lambda/add?x=1&y=2

AWS Chalice 用于在此处添加简单端点.

AWS Chalice was used for adding simple endpoints here.

@app.route('/{exp}', methods=['GET'])
def add(exp):
    app.log.debug("Received GET request...")
    request = app.current_request
    app.log.debug(app.current_request.json_body)
    x = request.query_params['x']
    y = request.query_params['y']
    if exp == 'add':
        app.log.debug("Received ADD command...")
        result = int(x) + int(y)
        return {'add': result}

基本上,它检查path是否等于add并求和来自query_params的两个值.

Basically, it checks if the path is equal to add and sums two values from query_params.

现在,我正在尝试在另一个lambda中调用此lambda.

Now, I am trying to invoke this lambda in another lambda.

我的问题:

如何使用boto3 lambda客户端将pathquery_params传递给我的原始lambda函数?

How I can pass the path and query_params to my original lambda function using boto3 lambda client?

到目前为止我尝试过的事情:

What I have tried so far:

我在policy.json文件中添加了两行,使我可以调用原始功能.

I added two lines to policy.json file that allow me to invoke original function.

我在StackOverflow上看到了很多类似的问题,但其中大多数都将有效载荷作为json传递.

I saw a lot of similar question on StackOverflow, but most of them pass payload as a json.

@app.route('/')
def index():
    lambda_client = boto3.client('lambda')
    invoke_response = lambda_client.invoke(
        FunctionName="function-name",
        InvocationType="RequestResponse"
    )
    app.log.debug(invoke_response['Payload'].read())

提前谢谢!

推荐答案

也许您可以将下一个代码添加到add函数中,因此它也可以接受有效载荷:

Maybe you can add the next code to your add function, so it accepts payloads too:

@app.route('/{exp}', methods=['GET'])
def add(exp, *args, **kwargs):
    if isinstance(exp, dict):
        # exp is event here
        request = exp.get('request', {'x': 0, 'y': 0})
        exp = exp.get('exp', 'add')

我将编写一个一般示例,您可以轻松地对其进行修改以满足您的需求.在您的情况下,数据字典将具有requestexp键,并且您需要找到lambda函数的arn.

I'm going to write a general example, and you can easily modify it to match your needs. In your case the data dictionary would have request and exp keys, and you need to find your lambda function's arn.

AWS文档Lambda.invoke

让我们从现在开始假设有2个Lambda,分别是"master"和"slave".主人会叫奴隶.

Let's assume from now on we have 2 Lambdas named "master" and "slave". master will call slave.

目前有3种类型的调用:

At the moment there are 3 types of invocations:

  1. RequestResponse(默认):主站调用并等待从站响应
  2. 事件:异步,主叫和忘记
  3. DryRun:在运行之前进行一些验证

我保持#1 RequestResponse:

I keep with #1 RequestResponse:

从站:

def lambda_handler(event, context):
    result = {}
    result['event'] = event
    result['result'] = "It's ok"
    return result

它的arn类似于arn:aws:lambda:us-east-1:xxxxxxxxxxxxxx:function:slave

在示例中,slave只是一个回显功能

In the example, slave is just an echo function

现在,母版需要具有必要角色的权限才能调用它,以及arn或名称.然后,您可以编写如下内容:

Now, the master needs the necessary role's permission to call it, and the arn or name. Then you can write something like this:

import boto3
from datetime import datetime
import json

client = boto3.client('lambda')

def lambda_handler(event, context):
    arn = 'arn:aws:lambda:us-east-1:xxxxxxxxxxxxxx:function:slave'
    data = {'my_dict': {'one': 1, 'two': 2}, 'my_list': [1,2,3], 'my_date': datetime.now().isoformat()}

    response = client.invoke(FunctionName=arn,
                             InvocationType='RequestResponse',
                             Payload=json.dumps(data))

    result = json.loads(response.get('Payload').read())
    return result

通常,您会使用os.environ.get('slave_arn')

所有来自/到lambda的数据都必须是JSON可序列化的.

All data from/to lambdas must be JSON serializable.

这篇关于AWS Lambda:使用boto3 invoke从另一个AWS lambda调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 23:14