【问题标题】:How to run lambda application as local API如何将 lambda 应用程序作为本地 API 运行
【发布时间】:2021-10-27 20:02:32
【问题描述】:

我到处寻找一些支持的库,但找不到任何东西。我只想将我的 lambda 作为本地 api 运行(即 localhost:80000/api/get/1),这样我就可以在我的机器上同时运行我的前端和后端以进行快速开发。

我已经组合了一个我在本地运行的 fastapi“网关”,并使用它在本地调用 lambda_entry,唯一的问题是它非常慢,毫无疑问,为每个请求启动环境会对性能造成负担。

我觉得这是人们会经常使用的东西,我走对了吗?

【问题讨论】:

  • 您在使用 AWS SAM 吗?还是只是原始的 AWS Lambda?
  • @NielGodfreyPonciano 我看过 SAM,但我的印象是用于测试 lambda 事件?我没有看到如何将它作为服务器运行并让它像生产 API 那样接受 HTTP 请求
  • 是的,它可以用于测试事件,但也可以用于生成本地 API。我添加了一个答案。希望它适合您的需求。
  • @NielGodfreyPonciano 非常感谢 :)

标签: python amazon-web-services aws-lambda aws-api-gateway


【解决方案1】:

您可以为此使用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

  • 这是您放置 Lambda 函数代码的地方。
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

【讨论】:

  • 我在运行 sam local start-api 时遇到问题。我已经在 docker 容器中,所以不确定如何安装 docker?
猜你喜欢
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
  • 2020-12-10
  • 2021-11-10
  • 1970-01-01
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多