您可以为此使用AWS SAM。
本地测试和调试
使用 SAM CLI 逐步调试和调试您的代码。它提供了一个
本地类似 Lambda 的执行环境,帮助您发现问题
预付款。
您可能需要先install Docker,因为它是用于运行 API 的执行环境。首先设置sam 项目。
$ python3 -m pip install aws-sam-cli
$ sam init # Just choose the first options e.g. <1 - AWS Quick Start Templates>
现在,您将拥有这样的文件结构:
$ tree
.
└── sam-app
├── events
│ └── event.json
├── hello_world
│ ├── app.py
│ ├── __init__.py
│ └── requirements.txt
├── __init__.py
├── README.md
├── template.yaml
└── tests
├── __init__.py
├── integration
│ ├── __init__.py
│ └── test_api_gateway.py
├── requirements.txt
└── unit
├── __init__.py
└── test_handler.py
6 directories, 13 files
您会感兴趣的 2 个文件是:
sam-app/hello_world/app.py
import json
def lambda_handler(event, context):
"""Sample pure Lambda function"""
return {
"statusCode": 200,
"body": json.dumps({
"message": "hello world",
}),
}
sam-app/template.yaml
- 您可以在此处配置 API,例如HTTP 方法、URL、要运行的代码的位置等
...
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.9
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
...
构建应用程序,然后您就可以运行本地 API
$ cd sam-app/
$ sam build
$ sam local start-api
访问您的本地 API
- 请注意,第一次运行它可能需要一些时间,因为这是设置 API 环境的时候,例如创建映像并运行容器。任何后续调用都应该很快。
$ curl http://127.0.0.1:3000/hello
{"message": "hello world"}
为您提供指导的完整参考:https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-getting-started-hello-world.html