仅使用AWS Lambda加载本地模块时出现故障



应用程序结构:

.
├── 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.7docker映像中运行它时,以及在AWS上部署时才会出现此错误。我的所有测试都通过了,它能够毫无问题地导入模块。

我是否应该在__init__.py文件中加载/设置某些内容?

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

您在这里使用的是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

最新更新