这节来学习一个经典的案例,这个案例我在三个不一样的培训视频里面都看见过,不知道最初的原创者是谁 :)python
和前面的几个例子比较起来,思路实际上是大同小异的,惟一的区别在于两点:linux
这个例子的流程简单的说就是建立2个S3的bucket,在其中一个上传照片,他会自动压缩尺寸并保存在另一个bucket里面。 下面来看看如何实现。json
首先建立2个bucket,一个source, 一个destinationide
而后建立对应的role函数
而后建立一个Lambda function,选择上面配置的role学习
添加一个触发器,这里咱们指定S3的source bucket测试
接下来,是配置对应的函数code
import os import tempfile import boto3 from PIL import Image s3 = boto3.client('s3') DEST_BUCKET = os.environ['DEST_BUCKET'] SIZE = 128, 128 def lambda_handler(event, context): for record in event['Records']: source_bucket = record['s3']['bucket']['name'] key = record['s3']['object']['key'] thumb = 'thumb-' + key with tempfile.TemporaryDirectory() as tmpdir: download_path = os.path.join(tmpdir, key) upload_path = os.path.join(tmpdir, thumb) s3.download_file(source_bucket, key, download_path) generate_thumbnail(download_path, upload_path) s3.upload_file(upload_path, DEST_BUCKET, thumb) print('Thumbnail image saved at {}/{}'.format(DEST_BUCKET, thumb)) def generate_thumbnail(source_path, dest_path): print('Generating thumbnail from:', source_path) with Image.open(source_path) as image: image.thumbnail(SIZE) image.save(dest_path)
注意!!!这个函数里面咱们调用了Pillow这个图片的模块,可是这个模块默认在aws的运行环境里面是没有的,所以咱们须要手动上传。orm
首先从 https://pypi.org/project/Pillow/#files 上面下载对应的linux whl 文件,whl文件实际上是一个压缩包,Windows 下面咱们能够用 wheel unpack 解压。若是在Linux环境下,能够直接用unzip打开。视频
而后把这个PIL文件夹和咱们的python文件一块儿zip
而后上传到Lambda的控制台
注意py文件和入口函数的名字要和handler匹配
也别忘记了配置环境变量
咱们能够经过测试模板来查看对应的事件的json格式
最后来看看运行效果
上传几个图片
自动压缩保存在另一个bucket里面
实验成功