Serverless 简明教程

Serverless - Deploying Function

Creating a New Project

导航到新的文件夹,你希望在其中创建第一个要部署到 Serverless 的项目。在该文件夹中,运行以下命令 −

Navigate to a new folder wherein you want to create your first project to be deployed to serverless. Within that folder, run the following command −

sls create --template aws-python3

此命令将创建样板代码,以使用 Serverless 和 Python 运行时部署 Lambda 函数。

This command will create the boilerplate code for deploying lambda functions using serverless and python runtime.

deploying

请注意,你还可以使用其他运行时。运行 sls create --help 以获取所有模板的列表。

Note that you can use other runtimes as well. Run sls create --help to get a list of all templates.

一旦创建了样板代码,你将在文件夹中看到两个文件:handler.py 和 serverless.yml。handler.py 是包含 Lambda 函数代码的文件。serverless.yml 是告诉 AWS 如何创建 Lambda 函数的文件。这是配置文件或设置文件,它将成为本教程中几个章节的重点。让我们首先了解 handler.py 文件。

Once the boilerplate code is created, you will see two files in your folder: handler.py and serverless.yml. handler.py is the file containing the lambda function code. serverless.yml is the file that tells AWS how to create your lambda functions. It is the configuration file or the settings file that is going to be the focus of several chapters of this tutorial. Let us go through the handler.py file first.

import json
def hello(event, context):
   body = {
      "message": "Go Serverless v1.0! Your function executed successfully!", "input": event
   }
   response = {
      "statusCode": 200, "body": json.dumps(body)
   }
   return response
   # Use this code if you don't use the http event with the LAMBDA-PROXY
   # integration
   """
   return {
      "message": "Go Serverless v1.0! Your function executed successfully!", "event": event
   }
   """

它包含一个函数 hello 。此函数接收两个参数:event 和 context。这两个参数都是任何 AWS Lambda 函数的必需参数。每当调用 Lambda 函数时,Lambda 运行时将两个参数传递给该函数 − event 和 context。

It contains one function hello. This function takes in two arguments: event and context. Both of these are required arguments for any AWS Lambda function. Whenever the lambda function is invoked, the lambda runtime passes two arguments to the function − event and context.

event 参数包含要由 Lambda 函数处理的数据。例如,如果你通过 REST API 触发 Lambda 函数,无论你发送到路径参数或 API 正文中的什么数据,都会在事件参数中发送到 Lambda 函数。更多内容请参见后面的章节。需要注意的重要一点是,虽然 event 通常是 Python dict 类型,但也可以是 strfloatintlistNoneType 类型。

The event argument contains the data for the lambda function to process. For instance, if you trigger your lambda function through a REST API, whatever data you send in the path parameters or the body of the API, are sent to the lambda function in the event parameter. More on that in later chapters. The important thing to note is that the event is usually of the python dict type, although can also be of str, float, int, list, or NoneType type.

context 对象是在运行时传递到你的 Lambda 函数的另一个参数。它并不常被使用。官方 AWS 文档指出,此对象提供有关调用、函数和运行时环境的信息的方法和属性。你可以阅读更多有关 eventcontext 对象的信息 here

The context object is another argument passed on to your lambda function at runtime. It is not used very often. The official AWS Documentation states that this object provides methods and properties that provide information about the invocation, function, and runtime environment. You can read more about the event and context objects here.

该函数非常简单。它只返回一条状态码为 200 的消息。底部有一条注释,如果我们不使用带 LAMBDA-PROXY 设置的 HTTP 事件,应该使用这条注释。更多内容请参见 API 触发的 Lambda 章节。

The function is pretty straightforward. It simply returns a message with status code 200. There is a comment at the bottom that should be used if we don’t use the HTTP event with the LAMBDA-PROXY setting.More on that in the API-triggered lambda chapter.

现在,让我们看看 serverless.yml 文件。这是一个很多注释的文件。对于刚开始接触 Serverless 的人来说,这些注释非常有用。我们鼓励你仔细阅读这些注释。在后面的章节中,我们将探讨很多与 serverless.yml 相关的概念。让我们先浏览一下这里的基本概念。

Now, let us look at the serverless.yml file. It is a heavily commented file. The comments are extremely useful for someone starting off with serverless. You are encouraged to go through the comments thoroughly. We will be looking at a lot of concepts related to serverless.yml in the upcoming chapters. Let us just skim through the basic concepts here.

如果你在删除注释后查看 serverless.yml 文件,它将如下所示 −

If you look at the serverless.yml file after removing the comments, this is how it will look like −

service: aws-serverless
frameworkVersion: '2'

provider:
   name: aws
   runtime: python3.8
   lambdaHashingVersion: 20201221
functions:
   hello:
      handler: handler.hello

service 区域确定 CloudFormation 堆栈的名称,你的 Lambda 函数和所有必需的资源都将在其中创建。认为 service 就是你的项目。执行 AWS Lambda 函数所需的一切都将在该 service 中创建。你可以根据自己的喜好设置一个 service 名称。

The service field determines the name of the CloudFormation stack within which your lambda function and all the required resources will be created. Think of the service as your project. Everything required for the AWS Lambda function to execute will be created within that service. You can set a service name of your choice.

framework version 是指 Serverless 框架的版本。它是一个可选区域,通常保留以确保与你分享代码的人使用相同的版本号。如果 serverless.yml 中提到的 frameworkVersion 与你机器中安装的 Serverless 版本不同,则你在部署期间会收到错误。你还可以为 frameworkVersion 指定一个范围,例如 frameworkVersion − >=2.1.0 && <3.0.0 。你可以阅读更多有关 frameworkVersions 的信息 here

The framework version refers to the version of the serverless framework. It is an optional field, ususally kept to ensure that the same version number is used by people with whom you share your code. If ther frameworkVersion mentioned in serverless.yml is different than the version of serverless installed in your machine, you will receive an error during deployment. You can also specify a range for frameworkVersion like frameworkVersion − >=2.1.0 && <3.0.0. You can read more about frameworkVersions here.

下一部分, provider ,可以看作是全局设置集合。我们将在以后的章节中讨论提供者中涵盖的附加参数。在此,我们重点关注现有的参数。 name 字段确定平台环境的名称,在这种情况下为 aws。运行时为 python3.8,因为我们使用了 python3 模板。lambdaHashingVersion 指的是框架应使用的 hash 算法的名称。

The next section, provider, can be considered as a set of global settings. We will be discussing additional parameters covered under provider in later chapters. Here, we will focus on the parameters available. The name field determines the name of your platform environment, which is aws in this case. The runtime is python3.8 because we used the python3 template. The lambdaHashingVersion refers to the name of the hashing algorithm that should be used by the framework.

请注意,如果你为上一章中的“config credentials”步骤添加了自定义配置文件,那么你需要在“provide”中添加“profile”参数。例如,我将我的配置文件名称设置为 yash-sanghvi。因此,我的提供者如下所示 −

Please note that if you’ve added a custom profile in the config credentials step in the previous chapter, you will need to add the profile parameter in provide. For instance, I set my profile name to yash-sanghvi. Therefore, my provider looks like −

provider:
   name: aws
   runtime: python3.8
   lambdaHashingVersion: 20201221
   profile: yash-sanghvi

最后,functions 块定义所有 lambda 函数。这里只有一个函数,在处理程序文件中。该函数的名称是 hello。处理程序字段中提到了该函数的路径。

Finally, the functions block defines all the lambda functions. We have just one function here, in the handler file. The name of the function is hello. The path of the function is mentioned in the handler field.

Deploying the function

要部署该函数,你需要打开命令提示符,导航到包含 serverless.yml 的文件夹,并输入以下命令 −

To deploy the function you need to open the Command Prompt, navigate to the folder containing your serverless.yml, and enter the following command −

sls deploy -v

-v 是指示详细输出的可选参数。它可以帮助你更好地理解后台进程。一旦函数部署完成,你应该能够在 us-east-1 区域(这是默认区域)的 AWS 控制台中看到它。你可以使用“测试”功能从控制台中对其进行调用(你可以保持相同的默认事件,因为我们的 lambda 函数根本不使用事件输入)。你还可以使用以下命令通过命令提示符进行测试 −

The -v is an optional argument that indicates verbose output. It helps you understand the background processes better. Once your function is deployed, you should be able to see it on the AWS Console in the us-east-1 region (which is the default). You can invoke it from the console, using the 'Test' feature (you can keep the same default event since our lambda function is anyway not using the event input). You can also test it using the Command Prompt using −

sls invoke --function hello

请注意,如果你通过诸如 S3 或 dynamoDB 等其他 AWS 服务与该函数进行接口,那么你不能总是本地测试该函数。只有非常基本的函数可以在本地进行测试。

Please note that you cannot always test your function locally if it interfaces with other AWS Services like S3 or dynamoDB.Only the very basic functions can be tested locally.

Deploying function from an existing project

如果你想将现有项目部署到 AWS,请修改现有函数以仅将 eventcontext 作为参数。接下来,在文件夹中添加一个 serverless.yml 文件,并在 serverless.yml 中定义你的函数。然后打开命令提示符,导航到该文件夹,然后点击 sls deploy -v 。这样,你的现有函数也可以部署到 AWS Lambda。

If you want to deploy an existing project to AWS, modify the existing function to take in only the event and context as arguments. Next, add a serverless.yml file in the folder, and define your function within serverless.yml. Then open the command prompt, navigate to the folder, and hit sls deploy -v. That way, your existing function can also be deployed to AWS Lambda.