在多个 AWS Lambda 中导入一个 python 模块
我有几个 AWS Lambda 函数.所有这些函数都使用一些常见的辅助函数.我将这些辅助函数放在一个名为 helper_functions.py
的单独文件中.我想在我所有的 AWS Lambda 函数中导入这个模块.我找不到存储此模块的位置 (helper_functions.py
),因此当我在此模块中进行更改时,我无需更改我的 Lambda 函数中的任何内容.
I have a couple of AWS Lambda functions. All of those functions use some common helper functions. I have placed these helper functions in a separate file called helper_functions.py
. I want to import this module in all of my AWS Lambda functions. I am unable to find a place to store this module (helper_functions.py
), so when I make a change in this module I don't have to change anything in my Lambda functions.
我想到的一些选项是:
在 AWS S3 上上传模块,然后在每个 Lambda 中加载函数从 S3 开始并使用函数.(如果可能)
Uploading the module on AWS S3 and then loading it in each Lambda function in the start from S3 and using the functions. (if possible)
编写一些脚本(我还没有弄清楚)将模块与 Lambda 打包在一起zip 中的函数 Python 文件并将其上传到 AWS Lambda
Writing some script (which I haven't figured out yet) that packages the module along with the Lambda functions' Python file in a zip and uploads it on AWS Lambda
请提出更好的解决方案来管理模块并以更有效的方式导入它.
Please suggest a better solution to manage the module and import it in a much more efficient way.
我为此苦苦挣扎了很长时间.这是我的解决方案(可能有更好的方法):
I struggled with this for a long time. Here's my solution (there might be a better way):
像这样在你的文件系统中设置你的辅助函数:
setup your helper function in your file system like this:
pathToSomewhere/my_helper/helper_functions.pypathToSomewhere/my_helper/__init__.pypathToSomewhere/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/
运行:
Now let's package up my_helper
. From pathToSomewhere/
run:
python setup.py sdist
我假设您已经知道如何创建和上传用于运行 lambda 函数的虚拟环境.如果没有,请告诉我.
I'm assuming you already know how to create and upload a virtual environment for running your lambda function. If not, let me know.
现在让我们将 my_helper
安装到 lambda 函数的虚拟环境中.假设您的虚拟环境名为 worker_env
Now let's install my_helper
into the virtual env of your lambda function. Let's assume your virtual environment is called worker_env
./worker-env/bin/pip install file://pathToSomewhere/my_helper
现在压缩 worker-env
和您的实际 lambda 脚本并上传.
Now zip up worker-env
and your actual lambda script and upload that.