lambda调用函数

In this article, I am going to explain how to create an AWS Lambda function and then call this function from another Lambda function within the same region. This is a useful scenario in which we may need to execute a second lambda function based on the outcome of some previous logic. Another scenario may be to execute a second lambda function several times by using different parameters.

在本文中,我将解释如何创建一个AWS Lambda函数,然后从同一区域内的另一个Lambda函数调用此函数。 这是一个有用的场景,其中我们可能需要根据某些先前逻辑的结果执​​行第二个lambda函数。 另一种情况可能是使用不同的参数多次执行第二个lambda函数。

For the sake of this article, we will consider a typical retailer application, in which we can purchase different products from a retailer site using a lambda function.

为了本文的目的,我们将考虑一个典型的零售商应用程序,在该应用程序中,我们可以使用lambda函数从零售商站点购买不同的产品。

If you consider the above architecture diagram, you can see that we have an AWS lambda function – the ParentFunction, which assumes a specific role from the IAM (Invoke Other Lambda Function) and then calls another lambda function – the ChildFunction with a payload. Once the execution of the ChildFunction is completed, it returns a response, which is then passed on to the ParentFunction. The ParentFunction receives the response and handles the job accordingly.

如果考虑以上架构图,您会看到我们有一个AWS lambda函数– ParentFunction ,它从IAM( 调用其他Lambda函数 )承担特定角色,然后调用另一个lambda函数–带有有效负载的ChildFunction 。 一旦ChildFunction的执行完成,它将返回一个响应,然后将其传递给ParentFunctionParentFunction接收响应并相应地处理作业。

As in this example, let us assume that the ParentFunction is going to call the ChildFunction with a payload of ProductName, Quantity, and the UnitPrice of that product. The ChildFunction, in turn, will process this payload, calculate the total sales amount, generate a transaction reference ID, and return this information to the ParentFunction.

在此示例中,让我们假设ParentFunction将使用该产品的ProductName,Quantity和UnitPrice的有效负载来调用ChildFunction 。 反过来, ChildFunction将处理此有效负载,计算总销售额,生成交易参考ID,并将此信息返回给ParentFunction

创建第一个AWS Lambda函数– ChildFunction (Creating the first AWS Lambda Function – ChildFunction)

Let us first go ahead and create the ChildFunction, which will process the input payload and return the results to the ParentFunction.

让我们首先继续创建ChildFunction,该函数将处理输入的有效负载并将结果返回给ParentFunction。

Head over to https://console.aws.amazon.com/ and login with your credentials. Once you are inside the console, start searching for “Lambda” and click on the first result that appears from the drop-down.

转到https://console.aws.amazon.com/并使用您的凭据登录。 进入控制台后,开始搜索“ Lambda ”,然后单击下拉菜单中显示的第一个结果。

This will take you to the Lambda Function homepage, where you can create a new lambda function by hitting the “Create Function” button.

这将带您到Lambda函数主页,您可以在其中单击“ 创建函数 ”按钮来创建新的lambda函数。

Let the name of this function be – “ChildFunction” and select Python 3.8 as the runtime.

将该函数的名称设为–“ ChildFunction”,然后选择Python 3.8作为运行时。

Select the option to Create a new role with basic lambda permissions and click on Create Function.

选择选项以创建具有基本lambda权限的新角色,然后单击创建功能

A new lambda function will be created where you can write your code and test it.

将创建一个新的lambda函数,您可以在其中编写代码并对其进行测试。

Let us now head over to Visual Studio Code and start writing our code for the ChildFunction as follows. This is a very simple application that is going to perform the following steps:

现在让我们转到Visual Studio Code,并开始为ChildFunction编写我们的代码,如下所示。 这是一个非常简单的应用程序,它将执行以下步骤:

  1. Read data from the ParentFunction 从ParentFunction读取数据
  2. Generate the Transaction Reference ID 产生交易参考编号
  3. Calculate the business information 计算业务信息
  4. Return the result to the Parent Function 将结果返回给父函数
import json
import uuiddef lambda_handler(event, context):#1 Read the input parametersproductName = event['ProductName']quantity    = event['Quantity']unitPrice   = event['UnitPrice']#2 Generate the Order Transaction IDtransactionId   = str(uuid.uuid1())#3 Implement Business Logicamount      = quantity * unitPrice#4 Format and return the resultreturn {'TransactionID' :   transactionId,'ProductName'   :   productName,'Amount'        :   amount}#########################################################################
# No need to include the following snippet into the lambda function
# Only used to test the function locally
event = {"ProductName"   : "iPhone SE","Quantity"      : 2,"UnitPrice"     : 499
}
response = lambda_handler(event,'')
print(response)
#########################################################################

Once the code is written and tested in the local machine, you can copy and paste the script to the lambda function to test it in AWS.

在本地计算机中编写和测试代码后,您可以将脚本复制并粘贴到lambda函数以在AWS中对其进行测试。

In order to test the ChildFunction, you need to create the Test Event, in which you can pass the payload information that we will be using to call from the ParentFunction. In order to configure test events, click on Test Event, and select Configure.

为了测试ChildFunction,您需要创建Test Event,在其中您可以传递我们将用于从ParentFunction调用的有效负载信息。 为了配置测试事件,请单击测试事件,然后选择配置

Give the test event a name and specify the payload information here to test it.

为测试事件命名,并在此处指定有效负载信息以对其进行测试。

Hit on Test to execute the ChildFunction with the payload information.

点击测试以使用有效负载信息执行ChildFunction

If the execution is successful, you will get a successful return with the calculations completed as follows. As you can see in the figure below, the function returns the following items.

如果执行成功,您将获得成功的回报,并完成以下计算。 如下图所示,该函数返回以下项目。

  1. Transaction ID 交易编号
  2. Product Name 产品名称
  3. Amount 量

This information will also be visible to the ParentFunction when it calls the ChildFunction.

当父函数调用子函数时,此信息也将对父函数可见。

Also, copy the ARN of the Child Function, which can be used later to apply for policies and roles upon.

同样,复制子功能的ARN,以后可用于在其上申请策略和角色。

设置ParentFunction的策略 (Setting up the Policy for ParentFunction)

In order to allow the ParentFunction to call the ChildFunction, we need to provide the ParentFunction with specific rights to call another lambda function. This can be done by adding specific policies to a role and then assign that role to the lambda function.

为了允许ParentFunction调用ChildFunction,我们需要为ParentFunction提供特定的权限来调用另一个lambda函数。 这可以通过向角色添加特定策略,然后将该角色分配给lambda函数来完成。

Head over to the IAM module inside the AWS portal and select Policies. Click on Create Policy to create a new one.

转到AWS门户内的IAM模块,然后选择策略 。 单击创建策略以创建一个新策略

In the Create Policy page, select the JSON tab and add the following policy summary to it as follows. Remember to update the URL for the Resource which you have copied in the previous step. Give the policy a suitable name and create it. I am going to name this policy as – “InvokeOtherLambdaPolicy”.

在“创建策略”页面中,选择“ JSON”选项卡,并向其添加以下策略摘要,如下所示。 记住要更新在上一步中复制的资源的URL。 为策略指定一个合适的名称并创建它。 我将这个策略命名为–“ InvokeOtherLambdaPolicy ”。

Navigate to the Roles and click on Create role.

导航到“ 角色” ,然后单击“ 创建角色”

Select Lambda as the use case and click on Next to add the required permissions.

选择Lambda作为用例,然后单击“下一步”添加所需的权限。

Add the following two policies to this role and create the role.

将以下两个策略添加到该角色并创建该角色。

  1. AWSLambdaBasicExecutionRole AWSLambdaBasicExecutionRole
  2. InvokeOtherLambdaPolicy 调用其他Lambda政策

Click on Next and proceed forward and create the role. Give this role a suitable name, for example, “InvokeOtherLambdaRole”.

单击下一步,然后继续并创建角色。 给该角色指定一个合适的名称,例如“ InvokeOtherLambdaRole ”。

创建AWS Lambda函数– ParentFunction (Creating the AWS Lambda Function – ParentFunction)

Head over to the Lambda Function page and click on Create New Lambda function. I am calling this lambda function – “ParentFunction”. Choose the run time as Python 3.8 and assign the InvokeOtherLambdaRole role that we just created in the previous step.

转到Lambda函数页面,然后单击创建新 Lambda函数。 我称这个lambda函数为“ ParentFunction ”。 选择运行时作为Python 3.8,并分配我们在上一步中刚刚创建InvokeOtherLambdaRole角色。

Let us now again head over to Visual Studio Code to write the code and then copy-paste it back to the lambda editor. Since we are going to use an AWS resource in this function, we need to use the Boto3 python library to use the AWS resources. This library can be used to interact with other AWS resources as and when required.

现在让我们再次转到Visual Studio Code来编写代码,然后将其复制粘贴回lambda编辑器。 由于我们将在此函数中使用AWS资源,因此我们需要使用Boto3 python库来使用AWS资源。 必要时,该库可用于与其他AWS资源进行交互。

import json
import boto3# Define the client to interact with AWS Lambda
client = boto3.client('lambda')def lambda_handler(event,context):# Define the input parameters that will be passed# on to the child functioninputParams = {"ProductName"   : "iPhone SE","Quantity"      : 2,"UnitPrice"     : 499}response = client.invoke(FunctionName = 'arn:aws:lambda:eu-west-1:890277245818:function:ChildFunction',InvocationType = 'RequestResponse',Payload = json.dumps(inputParams))responseFromChild = json.load(response['Payload'])print('\n')print(responseFromChild)

As you can see in the above code, we have created a boto client to interact with the lambda function. Also, we have created a payload that can be passed on to the ChildFunction when calling it. And once the ChildFunction is executed, it will return the response, which will be stored in the “response” variable.

如您在上面的代码中看到的,我们已经创建了一个boto客户端来与lambda函数进行交互。 同样,我们创建了一个有效载荷,可以在调用它时将其传递给ChildFunction。 并且一旦执行ChildFunction,它将返回响应,该响应将存储在“ response”变量中。

Finally, we can parse the payload information from the response and use it according to our needs. In this case, we are just going to print it on the screen. Copy the code from VS Code to the lambda editor.

最后,我们可以从响应中解析有效负载信息,并根据需要使用它。 在这种情况下,我们只是将其打印在屏幕上。 将代码从VS Code复制到lambda编辑器。

Create a sample test event for this function since we are not going to pass any payload for this Parent Function here. Save the event and click on the Test.

为此函数创建一个示例测试事件,因为在这里我们不会传递此父函数的任何有效负载。 保存事件,然后单击“ 测试”

Once you execute the ParentFunction, it will pass the payload information to the ChildFunction, where the result will be calculated, and then the final response will be sent back from the ChildFunction to the ParentFunction. You can see the execution logs and confirm this as follows.

一旦执行ParentFunction,它将把有效负载信息传递给ChildFunction,在此将计算结果,然后将最终响应从ChildFunction发送回ParentFunction。 您可以查看执行日志并按以下说明进行确认。

结论 (Conclusion)

In this article, I have explained how we can call or execute an AWS Lambda function from another lambda function within the same region. Using the AWS Lambda function, you can easily write serverless applications without having to worry about the infrastructure running behind it. Often, it becomes necessary that we might need to call different AWS Lambda functions from within another lambda due to the handling of complex business logic or something like that.

在本文中,我解释了如何从同一区域内的另一个lambda函数调用或执行AWS Lambda函数。 使用AWS Lambda函数,您可以轻松编写无服务器应用程序,而不必担心背后运行的基础架构。 通常,由于处理复杂的业务逻辑或类似的事情,我们可能有必要从另一个lambda中调用不同的AWS Lambda函数。

翻译自: https://www.sqlshack.com/calling-an-aws-lambda-function-from-another-lambda-function/

lambda调用函数

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数相关推荐

  1. python的lambda函数错误的是_Python 中的 AWS Lambda 函数错误 - AWS Lambda

    Python 中的 AWS Lambda 函数错误 当您的代码引发错误时,Lambda 将生成错误的 JSON 表示形式.此错误文档会出现在调用日志中,对于同步调用,它出现在输出中. 例 lambda ...

  2. python偏函数和高阶函数_【Python入门】8.高阶函数之 匿名函数和偏函数

    目录 高阶函数 匿名函数 lambda 偏函数 高阶函数 匿名函数 lambda lambda,即希腊字母λ.顾名思义,匿名函数没有函数名,在运用时采取lambda x : ...的方式,如lambd ...

  3. python len函数_知识清单Python必备的69个函数,你掌握了吗?

    本文纲要 Python 作为一门高级编程语言,为我们提供了许多方便易用的内置函数,节省了不少开发应用的时间.目前,Python 3.7 共有 69 个内置函数,一些是我们耳熟能详的函数,另一些却不是很 ...

  4. append函数_连载|想用Python做自动化测试?函数的参数传递机制及变量作用域

    " 这一节有点难.看不懂没关系.继续往后学,回头再来看." 10.6 函数参数传递的机制 10.6.1 值传递与引用传递 编程语言的参数传递机制通常有两种: 值传递 拷贝参数的值, ...

  5. memcpy函数_如何理解c语言中的回调函数

    在计算机程序设计中,回调函数,或简称回调,是指通过函数参数传递到其它代码的,某一块可执行代码的引用.这一设计允许了底层代码调用在高层定义的子程序. 这段话不是那么好理解,不同语言实现回调的方式有些许不 ...

  6. python类和函数_构建程序. Python中的类和函数

    如果希望mainfunc的所有实例都使用相同的KeySeq对象,则可以使用默认参数值技巧: def mainfunc(ks=KeySeq()): key = ks.next() 只要您实际上没有传递k ...

  7. 文件从头开始读函数_如何从头开始编写自己的Promisify函数

    文件从头开始读函数 介绍 (Introduction) In this article, you will learn how to write your own promisify function ...

  8. java中主函数_(基础)java中的主函数

    Java中的主函数 1.由JVM调用:JVM通过类名直接调用主函数(静态方法) 2.主函数的形参是一个字符串数组: String[] args 3.运行主函数时,如果没有向其传递参数,JVM会自动创建 ...

  9. python cursor函数_执行从python返回cursor的db2plsql函数

    我有一个pl-sql包,其中包含一个返回ref_cursor对象的函数. 下面是我的python代码,我在其中尝试调用该函数temp="" con = get_connection ...

最新文章

  1. Python使用numpy函数vsplit垂直(行角度)拆分numpy数组(返回拆分后的numpy数组列表)实战:垂直拆分二维numpy数组、split函数垂直拆分二维numpy数组
  2. 375. Guess Number Higher or Lower II
  3. spring mvc DispatcherServlet详解之前传---FrameworkServlet
  4. Spring Cloud构建微服务架构:服务消费(Feign)【Dalston版】
  5. (JAVA学习笔记) 冒泡排序算法
  6. linux 进程死循环,Linux下如何处理一次用户态进程死循环问题
  7. 搞懂Java分布式锁实现看这篇文章就对了
  8. 在preferences窗口找不到要运行的tomcat_基于docker安装tomcat例子
  9. 双向板受力特点_弹性减震球形钢支座/双向弹簧铰支座特性
  10. Mybatis框架的介绍以及详细使用,结合JDBC讲解,有利于对mybatis的注解和配置文件的理解,结合我上一篇文章,更好容易理解,通俗易懂,适合刚接触框架的新手(二)
  11. 关于图片格式中的那些“小”事---- 由编辑图片格式时所想到的
  12. HDU - 3966(树链剖分)
  13. Web前端大作业—— 饮食餐饮网站 咖啡网站pc端带轮播(5个页面)HTML+CSS+JavaScript 学生美食网页设计作品 学生餐饮文化网页模板
  14. 2019蓝桥杯本科B组C-C++决赛题 (题解随后出)
  15. 大数据技术之Linux
  16. javascript学习-canvas
  17. 沙沙野—让作品遇见全世界
  18. 日语二级语法汇总(part8/16)
  19. cocos2d获取手机IMEI
  20. 701升级800问题

热门文章

  1. js遍历对象方法总结
  2. Python之二维数组(list与numpy.array)
  3. 预防未成年人的犯罪法
  4. 墨者学院——来源页伪造
  5. IOS开发之——网络-服务器搭建(2)
  6. python二维向量运算,二维数组python中的矢量化计数
  7. jQuery 遍历祖先元素
  8. python写的链接搜索网站
  9. Nginx日志配置经验分享
  10. Spring Cloud Alibaba 发布毕业后的首个版本