首页 > 解决方案 > 为什么我的 AWS lambda 函数测试给了我 SSL 错误?

问题描述

我当前的 Lambda_function 代码是:(它的目的是在上传时将图像大小调整为 600x400,然后保存它们)

import boto3
import os
import pathlib
from io import BytesIO
from PIL import Image


s3 = boto3.resource('s3')

def delete_this_bucket(name):
    bucket = s3.Bucket(name)
    for key in bucket.objects.all():
        try:
            key.delete()
            bucket.delete()
        except Exception as e:
            print("SOMETHING IS BROKEN !!")

def create_this_bucket(name, location):
    try:
        s3.create_bucket(
            Bucket=name,
            CreateBucketConfiguration={
                'LocationConstraint': location
            }
        )
    except Exception as e:
        print(e)

def upload_test_images(name):
    for each in os.listdir('./testimage'):
        try:
            file = os.path.abspath(each)
            s3.Bucket(name).upload_file(file, each)
        except Exception as e:
            print(e)

def copy_to_other_bucket(src, des, key):
    try:
        copy_source = {
            'Bucket': src,
            'Key': key
        }
        bucket = s3.Bucket(des)
        bucket.copy(copy_source, key)
    except Exception as e:
        print(e)


def resize_image(src_bucket, des_bucket):
    size = 600, 400
    bucket = s3.Bucket(src_bucket)
    in_mem_file = BytesIO()
    client = boto3.client('s3')

    for obj in bucket.objects.all():
        file_byte_string = client.get_object(Bucket=src_bucket, Key=obj.key)['Body'].read()
        im = Image.open(BytesIO(file_byte_string))

        im.thumbnail(size, Image.ANTIALIAS)
        # ISSUE : https://stackoverflow.com/questions/4228530/pil-thumbnail-is-rotating-my-image
        im.save(in_mem_file, format=im.format)
        in_mem_file.seek(0)

        response = client.put_object(
            Body=in_mem_file,
            Bucket=des_bucket,
            Key='resized_' + obj.key
        )

def lambda_handler(event, context):
    bucket = s3.Bucket('bucketname1')

    for obj in bucket.objects.all():
        copy_to_other_bucket(bucket, 'bucketname1', obj.key)

    resize_image(bucket.name, 'bucketname1')


    print(bucket)

它说我的 ssl 验证有错误。

"errorMessage": "SSL validation failed for https://bucketname1.s3.eu-west-3.amazonaws.com/?encoding-type=url [Errno 2] No such file or directory",
  "errorType": "SSLError",

任何人都可以帮我解决问题吗?我认为这可能是代码问题或某些 AWS lambda 设置配置问题。

标签: pythonamazon-web-servicessslamazon-s3aws-lambda

解决方案


您正在调用im.save()将图像保存到本地文件。您将https://bucketname1.s3.eu-west-3.amazonaws.com/?encoding-type=url作为文件路径传递以将其保存到。这是 S3 中对象的 URL,而不是库可以将文件保存到的本地路径。所以它给了你这个错误,因为它不知道如何将文件保存到那个位置。

由于您接下来要做的是使用 boto3 将文件上传到 S3,并且您似乎试图将图像保存在内存中而不是将其写入磁盘,所以我很确定您可以删除该im.save()行。如果确实需要调用im.save(),则必须在/tmp文件夹中为其指定路径,因为这是 Lambda 执行环境中您具有写入权限的唯一文件夹。


推荐阅读