[英]Project (AWS CDK) and Lambda specific python imports
Image you are writing an IaaC (Infrastructure as a Code) project with python programming language.图像您正在使用 Python 编程语言编写 IaaC(基础设施即代码)项目。 There is a good library/sdk that makes it convenient: AWS CDK (Amazon web services cloud development kit).有一个方便的库/sdk:AWS CDK(亚马逊网络服务云开发工具包)。 In the same project you can specify lambda source code too.在同一个项目中,您也可以指定 lambda 源代码。
Now imagine you want that python imports in the lambda function source code would work in the lambda environment and in the project.现在假设您希望 lambda 函数源代码中的 python 导入在 lambda 环境和项目中工作。 One of the simplest ways to achieve that is to try/except ImportError like this:实现这一目标的最简单方法之一是像这样尝试/排除 ImportError :
try:
# Lambda-specific import.
from some.path import PathModule
except ImportError:
# Project-specific import.
from iaac.project.source.some.path import PathModule
However, this solution seems to be kinda ugly.然而,这个解决方案似乎有点难看。 Any better suggestions how to write imports that would work in the AWS CDK project and in the Lambda environment?任何更好的建议如何编写在 AWS CDK 项目和 Lambda 环境中工作的导入?
Is it possible to use the same path for both the Lambda environment and the local environment?是否可以对 Lambda 环境和本地环境使用相同的路径?
If you pack the module together with the lambda source code, then from iaac.project.source.some.path import PathModule
should work both locally and in Lambda environment.如果您将模块与 lambda 源代码打包在一起,那么from iaac.project.source.some.path import PathModule
应该可以在本地和 Lambda 环境中工作。
If you put the module into a lambda layer , then you can install that module locally using pip
, and from some.path import PathModule
should work for both.如果您将模块放入lambda 层,那么您可以使用pip
在本地安装该模块,并且from some.path import PathModule
应该适用于两者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.