为什么在为 Python 创建自定义 AWS Lambda 层时无法导入模块?

dar*_*rse 2 python amazon-web-services aws-lambda aws-lambda-layers

我有一个名为 的模块custom_module.py,其中包含我想在几个不同的 Lambda 中使用的函数和方法。代码如下所示:

def test():
    return 'Custom module'
Run Code Online (Sandbox Code Playgroud)

我尝试通过压缩该文件并使用表单创建一个层来将其转换为 Lambda 层。一切似乎都运行良好,我将模块导入到 Lambda 中使用,如下所示:

import json
from custom_module import test

print('Loading function')

def lambda_handler(event, context):
    return test()
Run Code Online (Sandbox Code Playgroud)

不幸的是,运行它会返回一个"Unable to import module 'lambda_function': No module named 'custom_module'"错误。我到底做错了什么?我还指定了正确的运行时和架构。

编辑

根据评论,我尝试了这个文件结构:

layer
|
+--- python
     |
     +--- custom_module
          |
          +--- __init__.py (contains the test() method)
Run Code Online (Sandbox Code Playgroud)

layer我将文件夹压缩layer.zip并上传。不幸的是仍然遇到同样的问题。

Erm*_*ary 8

根据文档,对于 Python 运行时,Lambda 层应该只调用 1 个子文件夹python,以便 Lambda 可以访问层内容而无需指定路径(或者它需要是 内的站点包python/lib/python3.9/site-packages)。

您有 2 个子文件夹 -layer然后是python.

更改您的文件结构,使其仅custom_module包含在python文件夹内。

layer.zip
|
+--- python
     |
     +--- custom_module
          |
          +--- __init__.py (contains the test() method)
Run Code Online (Sandbox Code Playgroud)