首页 > 解决方案 > 如果图像尚不存在,如何将图像上传到 S3 存储桶

问题描述

我有一个 python 脚本运行,每小时将图像上传到 s3 存储桶。传入的图像分为三种类型,脚本根据图像名称创建一个特定文件夹,然后根据图像名称将图像上传到 S3 中的该文件夹。

现在发生的情况是,每隔一小时,相同的图像就会在存储桶中被覆盖,只有当图像不存在时我才需要上传图像我该如何实现这一点。请帮助通过

import os.path, shutil
import os, time
import socket
import boto3
from botocore.exceptions import NoCredentialsError
import glob
import json
from apscheduler.schedulers.blocking import BlockingScheduler


id = id_of_file
def my_schedule():
    s3 = boto3.client('s3', aws_access_key_id="Access_key",
                aws_secret_access_key="Secret_key")

    folder_path = "path"
    images = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
    for image in images:
        print(image)
        folder_name = image.split('-')[0]
        print(folder_name)
        print("folder created**********************************")
        key = "%s/%s" % (id+ '/' + folder_name, os.path.basename(image))
        objs = list(bucket.objects.filter(Prefix=key))
        print("Putting %s as %s" % (image, key))
        final_file = folder_path + image
        s3.upload_file(final_file, Bucket, key)

    print("ALL Images uploaded successfully to s3 bucket")
    time.sleep(5)

scheduler = BlockingScheduler()
scheduler.add_job(my_schedule, 'interval', hours=1)
scheduler.start()

标签: pythonamazon-s3

解决方案


推荐阅读