我正在尝试在 AWS Lambda 函数中 pip install 包。
Amazon 推荐的方法是创建一个压缩的部署包,其中包含依赖项和 python 函数(如Python 中的 AWS Lambda 部署包 https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html)。但是,这会导致无法在 AWS Lambda GUI 中使用内联代码编辑来编辑 Lambda 函数。
因此,我想在 AWS Lambda 函数本身内 pip 安装该包。在 AWS Lambda 中,除了 /tmp/ 目录之外,文件系统是只读的,因此我尝试将 pip 安装到 /tmp/ 目录。该函数每天仅调用一次,因此我不介意每次运行该函数时重新安装软件包所需的几秒钟时间。
我的尝试
def lambda_handler(event, context):
# pip install dependencies
print('begin lambda handler')
import subprocess
import sys
subprocess.call('pip install cryptography -t /tmp/ --no-cache-dir'.split())
from cryptography.fernet import Fernet
pwd_encrypted = b'gAAAAABeTcT0OXH96ib7TD5-sTII6jMfUXPhMpwWRCF0315rWp4C0yav1XAPIn7prfkkA4tltYiWFAJ22bwuaj0z1CKaGl8vTgNd695SDl25HnLwu1xTzaQ='
key = b'fP-7YR1hUeVW4KmFmly4JdgotD6qjR52g11RQms6Llo='
cipher_suite = Fernet(key)
result = cipher_suite.decrypt(pwd_encrypted).decode('utf-8')
print(result)
print('end lambda handler')
但是,这会导致错误
[错误] ModuleNotFoundError:没有名为“加密”的模块
我也尝试过更换子流程按照以下建议进行调用这个 stackoverflow 答案 https://stackoverflow.com/a/50255019/11918892
cmd = sys.executable+' -m pip install cryptography -t dependencies --no-cache-dir'
subprocess.check_call(cmd.split())
但是,这会导致错误
OSError: [Errno 30] 只读文件系统: '/var/task/dependencies'
我通过对最初尝试的一行调整解决了这个问题。您只需将 /tmp/ 添加到 sys.path 中,以便 Python 知道在 /tmp/ 中搜索该模块。您需要做的就是添加以下行sys.path.insert(1, '/tmp/')
.
Solution
import os
import sys
import subprocess
# pip install custom package to /tmp/ and add to path
subprocess.call('pip install cryptography -t /tmp/ --no-cache-dir'.split(), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
sys.path.insert(1, '/tmp/')
from cryptography.fernet import Fernet
def lambda_handler(event, context):
# pip install dependencies
pwd_encrypted = b'gAAAAABeTcT0OXH96ib7TD5-sTII6jMfUXPhMpwWRCF0315rWp4C0yav1XAPIn7prfkkA4tltYiWFAJ22bwuaj0z1CKaGl8vTgNd695SDl25HnLwu1xTzaQ='
key = b'fP-7YR1hUeVW4KmFmly4JdgotD6qjR52g11RQms6Llo='
cipher_suite = Fernet(key)
result = cipher_suite.decrypt(pwd_encrypted).decode('utf-8')
print(result)
Output
你好,堆栈溢出!
注意 - 正如 @JohnRotenstein 在评论中提到的,添加 Python 包的首选方法是将依赖项打包在AWS Lambda 层 https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html。我的解决方案只是表明可以直接在 AWS Lambda 函数中 pip install 包。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)