Skip to main content
 首页 » 编程设计

python之在多个 AWS Lambda 中导入一个 python 模块

2024年10月17日9kuangbin

我有几个 AWS Lambda 函数。所有这些函数都使用一些常见的辅助函数。我已将这些辅助函数放在一个名为 helper_functions.py 的单独文件中。我想在我的所有 AWS Lambda 函数中导入此模块。我无法找到存储此模块的位置 (helper_functions.py),因此当我更改此模块时,我不必更改 Lambda 函数中的任何内容。

我想到的一些选项是:

  1. 在 AWS S3 上上传模块,然后在每个 Lambda 中加载它 从 S3 开始并使用函数。 (如果可能的话)

  2. 编写一些脚本(我还没有弄清楚)将模块与 Lambda 一起打包 函数的 Python 文件压缩并上传到 AWS Lambda

请提出一个更好的解决方案来管理模块并以更有效的方式导入它。

请您参考如下方法:

我为此纠结了很长时间。这是我的解决方案(可能有更好的方法):

像这样在你的文件系统中设置你的辅助函数:

pathToSomewhere/my_helper/helper_functions.py pathToSomewhere/my_helper/__init__.py pathToSomewhere/setup.py

__init__.py 是:

from .helper_functions import * 

和setup.py是

from setuptools import setup 
 
setup(name='my_helper', 
      version='0.10000', 
      description='My helper functions', 
      url='http://github.com/user/example', 
      license='Proprietary', 
      author='Null', 
      author_email='null@example.com', 
      packages=['my_helper'], 
      install_requires=['boto3'], 
      zip_safe=False) 

现在让我们打包my_helper。从 pathToSomewhere/ 运行:

python setup.py sdist 

我假设您已经知道如何创建和上传用于运行 lambda 函数的虚拟环境。如果没有,请告诉我。

现在让我们将 my_helper 安装到您的 lambda 函数的虚拟环境中。假设您的虚拟环境名为 worker_env

./worker-env/bin/pip install file://pathToSomewhere/my_helper 

现在压缩 worker-env 和您实际的 lambda 脚本并上传。