【问题标题】:Issue with AWS Sam invoking local lambdaAWS Sam 调用本地 lambda 的问题
【发布时间】:2021-05-26 23:12:21
【问题描述】:

我有一个 python lambda,它只是示例 hello_world,您可以使用 sam init 创建它。

我稍微修改了一下,在 lambda 文件夹中添加了子文件夹。

所以在 hello_world lambda 文件夹中我有:

app.py # this is the lambda handler
requirements.txt
my_code_folder # I added this and I want to be able to import it and use it in the lambda. It contains a tonne of custom modules.

但是,当我运行 sam local invoke 时,我得到:

[ERROR] Runtime.ImportModuleError: Unable to import module 'app': No module named 'hello_world'

如果我取出导入,它工作正常。

也许我在我的 lambda 中导入错误?

import hello_world.my_code_folder.MyModule as my_module

我的 SAM 模板有这个:

Globals:
  Function:
    Timeout: 3

Resources:
  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.8
      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

【问题讨论】:

  • 您能否在打包的 ZIP 文件(包括 app.py 和 MyModule.py)中包含模块子集的列表?
  • 我认为导入应该是import my_code_folder.hello_world as mymodule

标签: python amazon-web-services aws-lambda aws-sam aws-sam-cli


【解决方案1】:

使用sam init 命令创建的示例应用并添加了一个名为hello 的自定义模块

❯❯ cat hello_world/hello/hello_world.py
# custom module
def hello():
    print("hello")
❯❯ cat hello_world/app.py
import json
import hello.hello_world as h


def lambda_handler(event, context):
...
    h.hello()

    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello world",
            # "location": ip.text.replace("\n", "")

目录结构

/tmp/foo/samapp via ? v3.8.2 ((samapp))
❯❯ tree
.
..
├── __init__.py
├── events
│   └── event.json
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   ├── hello. <--- my custom module
│   │   └── hello_world.py
│   └── requirements.txt
├── samconfig.toml
├── template.yaml

上传的代码

日志

【讨论】:

    猜你喜欢
    • 2021-04-01
    • 1970-01-01
    • 2020-05-27
    • 2020-11-11
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多