【问题标题】:Trouble loading local modules only with AWS Lambda仅使用 AWS Lambda 加载本地模块时遇到问题
【发布时间】:2019-05-18 02:19:29
【问题描述】:

应用结构:

.
├── Makefile
├── Pipfile
├── Pipfile.lock
├── README.md
├── template.yaml
├── tests
│   ├── __init__.py
│   └── unit
│       └── lambda_application
│           ├── test_handler.py
│           └── test_parent_child_class.py
└── lambda_application
    ├── __init__.py
    ├── first_child_class.py
    ├── lambda_function.py
    ├── second_child_class.py
    ├── requirements.txt
    └── parent_class.py

4 directories, 14 files

来自lambda_function.py的代码示例:

import os
import json
from hashlib import sha256
import boto3
from requests import Session
from .first_child_class import FirstChildClass


def lambda_handler(event, context):
    # Do some stuff.

按原样,我收到错误消息“无法导入模块 'lambda_function'”,但如果我注释掉最后一个导入“from .first_child_class import FirstChildClass”,它能够通过该部分并得到错误我还没有为那个类加载模块。

当我在 lambci/lambda:python3.7 docker 映像中运行它以及在 AWS 上部署时,我似乎只会收到此错误。我所有的测试都通过了,它能够毫无问题地导入模块。

我应该在__init__.py 文件中加载/设置什么吗?

编辑我更改了一些文件的名称以将其发布在此处。

【问题讨论】:

    标签: python python-3.x amazon-web-services aws-lambda


    【解决方案1】:

    您在此处使用relative import,以防您正在执行的代码位于模块中。但是,由于您的代码不是作为模块执行的,因此您的 AWS Lambda 会失败。

    https://stackoverflow.com/a/73149/6391078

    在本地快速运行出现以下错误:

    Python 3.6

    Traceback (most recent call last):
      File "lambda_function.py", line 4, in <module>
        from .first_child_class import FirstChildClass
    ModuleNotFoundError: No module named '__main__.first_child_class'; '__main__' is not a package
    

    您的测试通过了,因为您的测试套件将文件作为 modulelambda_application 文件夹中导入,该文件夹在测试模块中被视为一个包


    这让我朝着正确的方向前进,但并没有给我答案,但确实引导我找到答案,所以我想我会更新我在这里找到的内容。

    我没有尝试过,但根据我的发现,我相信:

    from first_child_class import FirstChildClass

    将是最简单的解决方案。

    我最终做的是将类移动到一个子目录中,基本上和上面一样,但前面加上了一个包名。

    所以,文件结构改为:

    .
    ├── Makefile
    ├── Pipfile
    ├── Pipfile.lock
    ├── README.md
    ├── template.yaml
    ├── tests
    │   ├── __init__.py
    │   └── unit
    │       └── lambda_application
    │           ├── test_handler.py
    │           └── test_parent_child_class.py
    └── lambda_application
        ├── __init__.py
        └── lib
            ├── first_child_class.py
            ├── second_child_class.py
            └── parent_class.py
        ├── lambda_function.py
        └── requirements.txt
    

    我的导入变成了from lib.first_child_class import FirstChildClass

    【讨论】:

    • 现在更有意义了。我现在才确定我需要如何修复它。
    • 如果答案解决了您的问题,请考虑将其标记为正确答案
    猜你喜欢
    • 2022-07-02
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2012-07-11
    • 2015-11-02
    相关资源
    最近更新 更多