Hay*_*den 4 python amazon-web-services python-3.x 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
Run Code Online (Sandbox Code Playgroud)
来自的代码示例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.
Run Code Online (Sandbox Code Playgroud)
照原样,我收到错误消息“无法导入模块'lambda_function'”,但是如果我注释掉了最后一个导入,“从.first_child_class import FirstChildClass”,它可以越过该部分并得到我没有的错误。为该类加载了模块。
当我在lambci / lambda:python3.7 docker映像中运行该错误以及在AWS上进行部署时,似乎只会出现此错误。我所有的测试都通过了,它能够毫无问题地导入模块。
我应该在__init__.py文件中加载/设置一些内容吗?
编辑我更改了一些文件的名称以将其发布在这里。
您正在使用relative import此处,以防您正在执行的代码在模块中。但是,由于您的代码不是作为模块执行的,因此您的AWS Lambda将失败。
在本地快速运行会出现以下错误:
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
Run Code Online (Sandbox Code Playgroud)
您的测试通过了,因为您的测试套件module从lambda_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
Run Code Online (Sandbox Code Playgroud)
我的进口变成 from lib.first_child_class import FirstChildClass
| 归档时间: |
|
| 查看次数: |
1228 次 |
| 最近记录: |