当我尝试部署lambda包时也遇到了同样的问题,问题在于必须预编译包以模拟要使用的lambda架构/运行时,否则你会得到“无法导入名称_imaging”的错误。解决此问题有两种方法:
1-启动一个EC2 Amazon Linux实例。(我只讨论这个方法)
2-使用docker。
简短解决方案
- 在 Amazon Linux 2 实例中安装 Python 3。(必须是您计划在 Lambda 中使用的 python3.X 版本)
- 在 ec2-user 主目录下安装虚拟环境。
- 激活环境,然后安装 Boto 3。
- 安装 Pillow。
- 创建一个 ZIP 归档文件,其中包含库(PIL 和 Pillow.libs)的内容。
- 将您的函数代码添加到归档文件中。
- 更新您的 Lambda。(AWS CLI)
长解决方案
- 如果尚未安装Python 3,则使用yum软件包管理器安装该软件包。
`$ sudo yum install python3 -y`
- 在 ec2-user 主目录下创建一个虚拟环境
The following command creates the app directory with the virtual environment inside of it. You can change my_app to another name. If you change my_app, make sure that you reference the new name in the remaining resolution steps.
`$ python3 -m venv my_app/env`
- 激活虚拟环境并安装Boto 3
将适当的权限策略与AWS Identity and Access Management (IAM)角色附加到您的EC2实例,以便Boto 3可以与AWS APIs进行交互。对于其他身份验证方法....为了快速使用,您可以使用 $ aws confifure
查看文档 设置您的凭据(在步骤7中需要)
3.1 通过在项目目录下的bin目录中的activate文件中运行源代码来激活环境。
`$ source ~/my_app/env/bin/activate`
3.2. 确保您的环境中已安装最新的pip模块。
$ pip install pip --upgrade
3.3 使用pip命令在虚拟环境中安装Boto 3库。
`pip install boto3`
使用pip安装库。
$ pip install Pillow
4.1 取消虚拟环境。
`$ deactivate`
创建一个包含库内容的ZIP归档文件。
切换到pip安装的目录,应该类似于/my_app/env/lib/python3.x/site-packages。
重要提示:关键在于将site-packages中的文件压缩成lambda所需的文件。(我只使用了PIL和Pillow.libs以节省空间,但你可以压缩所有文件)
5.1 压缩PIL文件夹中的所有内容。
`zip -r9 PIL.zip ./PIL/`
add the Pillow.libs to your ZIP
`zip -gr PIL.zip Pillow.libs`
-
Add your function code to the archive.
you can do this in the console if it just on file of code, but i recomend doing it in this step.If you don't have your code,just create a file using vi or nano and save it with the name that your lambda handler will use (in this case will use lambda_function.py).
`zip -g PIL.zip lambda_function.py`
Update your the lambda.(AWS CLI)
if you haven't create a lambda function,do it now before updating the function from the aws cli, make sure that you have the right permission to update lambda from the aws cli.
change LAMBDAFUNCTIONNAME for your function name
aws lambda update-function-code --function-name LAMBDAFUNCTIONNAME P --zip-file fileb://PIL.zip
走出第一个循环地狱
前往您的Lambda控制台并测试您的代码,请确保使用与EC2实例中使用的相同的运行时/Python版本。