python - Python 中的 AWS Lambda : Import parent package/directory in Lambda function handler

标签 python python-3.x aws-lambda aws-sam aws-sam-cli

我在使用 AWS SAM 和 Python 3.8 作为运行时创建的无服务器应用程序(避免困惑的最简单应用程序)中有如下目录结构:

├── common
│   └── a.py
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   └── requirements.txt
└── template.yaml

我要导入 common/a.py Lambda 处理程序中的模块 - hello_world/app.py .现在我知道我可以import it normally in Python通过将路径添加到 PYTHONPATHsys.path ,但是当代码在 Docker 容器内的 Lambda 中运行时,它不起作用。调用时,Lambda 处理程序函数在 /var/task 内部运行不考虑目录和文件夹结构。

我尝试插入 /var/task/common , /var/common , /var甚至/commonsys.path像这样以编程方式:
import sys
sys.path.insert(0, '/var/task/common')
from common.a import Alpha

但我仍然收到错误:
ModuleNotFoundError: No module named 'common'
我知道 Lambda Layers 但考虑到我的场景,我想直接引用多个 Lambda 函数中的公共(public)代码,而不需要上传到层。我想要 serverless-python-requirements 之类的东西 中的插件无服务器框架 但在 AWS SAM 中。

所以我的问题是,我应该如何将此路径添加到 commonPYTHONPATHsys.path ?或者是否有其他解决方法,例如 [serverless-python-requirements][3]直接在父文件夹中导入模块而不使用 Lambda 层?

最佳答案

我在包依赖项方面遇到了类似的问题,根据 AWS 知识中心,您应该将所有项目放在根级别:

You might need to create a deployment package that includes the function modules located in the root of the .zip file with read and execute permissions for all files.


根据https://aws.amazon.com/premiumsupport/knowledge-center/build-python-lambda-deployment-package/

关于python - Python 中的 AWS Lambda : Import parent package/directory in Lambda function handler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59764018/

相关文章:

python - 从 errbot 将数据返回到 Slack

python-3.x - 抓取 + 飞溅 : not rendering full page javascript data

Python Lambda 计数/循环函数

python - 从 np.empty 初始化 numpy 数组

python - MacOS stil 指向 python3.6

python - 如何获取2个连续记录之间的 "time difference"?

python - 如何列出列表中句子中某个单词的索引?我不明白它是如何工作的

node.js - 如何将 headless Chrome 模块与AWS Lambda捆绑在一起?

java - AWS Lambda : return type String is not compatible with POJOClass

node.js - 从具有相同跟踪 ID 的代码中调用 lambda?