我对python比较陌生,对Lambda也比较陌生。我已经创建了一个需要一些外部依赖项(elasticsearch和elasticsearch-curator)的lambda函数。
我的根文件夹名为index_curator,其中只有一个python文件main.py。根据亚马逊的instructions,我通过pip安装了依赖项。
pip install elasticsearch elasticsearch-curator -t /path/to/index_curator现在这个根目录和许多子目录中还有许多其他文件,这并不奇怪,因为这些依赖项非常大。对于其他查看此包的人来说,很难区分我编写的文件和外部依赖项。例如:
index_curator/
dateutil/
click/
idna/
main.py <-- the only file I wrote
README
LICENSE
six.py
...有没有办法将所有这些外部依赖项转移到子文件夹中,例如
index_curator/
/external/
dateutil/
click/
idna/
README
LICENSE
six.py
main.py <-- the only file I wrote为了完整起见,main.py中的导入是:
from elasticsearch import Elasticsearch, RequestsHttpConnection
import curator如有任何建议,我们将不胜感激。
发布于 2018-08-02 21:56:59
将外部依赖项与您的代码分离无疑是最佳实践。在python中有许多方法可以实现这一点。
默认情况下,python在指定的here位置搜索模块。要指定一个额外的位置(即您的external依赖文件夹),必须将这个新位置添加到python路径。您可以在main.py中执行此操作,如下所示:
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), 'external')))然后,您将能够像往常一样导入所有依赖项,因为解释器将在运行时检查额外的文件夹:
from elasticsearch import Elasticsearch, RequestsHttpConnection
import curator有关更多详细信息,请查看答案here
由于您的代码将是一个lambda函数,因此您将始终拥有一个处理程序。但对于更一般的情况,或者如果您开始编写多个文件,并需要管理这些文件中的外部依赖关系-您可以选择维护一个context.py文件,它设置依赖关系路径和所有导入,如下所示:
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), 'external')))
import elasticsearch
import context然后,在您的文件中,您可以使用以下命令调用它们:
from context.elasticsearch import Elasticsearch, RequestsHttpConnection
import context.curatorhttps://stackoverflow.com/questions/51622773
复制相似问题