我刚开始使用AWS无服务器框架SAM,遇到了以下问题:
SAM调用似乎找不到我Lambda处理程序正在导入的Python模块,但我可以导入该模块。
我的项目结构如下:
根目录/ - mymodulename/ - mymodule.py - aws/ - sam/ - template.yaml - packaged.yaml - myawsservice/ - app.py - test/ - test_event.json
我正在使用Python3.6虚拟环境工作,并使用设置工具安装了我的Python包(mymodulename)。
SAM调用似乎找不到我Lambda处理程序正在导入的Python模块,但我可以导入该模块。
我的项目结构如下:
根目录/ - mymodulename/ - mymodule.py - aws/ - sam/ - template.yaml - packaged.yaml - myawsservice/ - app.py - test/ - test_event.json
我正在使用Python3.6虚拟环境工作,并使用设置工具安装了我的Python包(mymodulename)。
python setup.py develop
如果我在虚拟环境中执行 pip freeze 命令,我将看到以下内容:
Pillow==6.0.0
PyPDF2==1.26.0
reportlab==3.5.20
mymodulename==0.5.0
同时如果我离开:
cd root-dir/aws/sam/
python
>>> import mymodulename
这个成功了,所以它在Python路径上。
但是当我在本地调用Sam时,即:
sam local invoke MyAWSServiceFunction --event ../sam/test/test_event.json
我收到了错误消息:
2019-05-02 09:19:17 Found credentials in shared credentials file: ~/.aws/credentials
2019-05-02 09:19:18 Invoking app.lambda_handler (python3.6)
Fetching lambci/lambda:python3.6 Docker container image......
2019-05-02 09:19:19 Mounting /home/myname/root-dir/aws/sam/myawsservice as /var/task:ro,delegated inside runtime container
START RequestId: 245daefe-ecfb-4530-9d15-cf07f55e0f3d Version: $LATEST
Unable to import module 'app': No module named 'mymodulename'
END RequestId: 245daefe-ecfb-4530-9d15-cf07f55e0f3d
REPORT RequestId: 245daefe-ecfb-4530-9d15-cf07f55e0f3d Duration: 31 ms
Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 19 MB
{"errorMessage": "Unable to import module 'app'"}
这是我的app.py的代码:
from mymodulename.mymodule import mymodulefunction
def lambda_handler(event, context):
return mymodulefunction(event['body'])
我可以在我的单元测试中运行上述代码,但无法从sam调用环境中运行。
template.yaml:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: > something
Globals:
Function:
Timeout: 3
Resources:
MyAWSServiceFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: myawsservice/
Handler: app.lambda_handler
Runtime: python3.6
需要帮助。
编辑:
一个解决方法是将app.py、requirements.txt和template.yaml放在根目录中,然后执行:
sam build
这将把第三方依赖和我的Python模块一起存储,template.py 现在可以在 sam local invoke 中找到它。
然而对于更大的项目,这不太实际,我想现在的答案可能是类似于这个。虽然这是针对 serverless.yaml 的,但我不确定 SAM 是否支持这种语法。猜测不支持。