首页 > 解决方案 > 使用 boto3 检查是否仍有任何文件需要上传到 Amazon S3

问题描述

我有下面的代码在本地保存文件,将其上传到我的 Amazon S3 存储桶,然后将其删除。

 filename = os.path.join(directory, '{}.mp3'.format(name_of_file))
            wf = wave.open(filename, 'wb')
            wf.setnchannels(CHANNELS)
            wf.setsampwidth(self.p.get_sample_size(FORMAT))
            wf.setframerate(RATE)
            wf.writeframes(recording)
            #this will be wher lambda function will go
            self.upload_file(filename, bucketName, name_of_file)
            delete_name = name_of_file
            name_of_file = file_name
            wf.close()
            os.remove(filename)

def upload_file(self, file_name, bucket, object_name):
    """Upload a file to an S3 bucket
    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """

    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = file_name

    # Upload the file
    s3_client = boto3.client('s3')
    try:
        response = s3_client.upload_file(file_name, bucket, '{}.mp3'.format(file_prefix + '/' + object_name), ExtraArgs={'ACL':'public-read'})
        
    except ClientError as e:
        pass
    return True

该代码工作正常,并且符合预期,但是,我想实现一种能够解决互联网中断或无关故障的机制。当脚本运行时,我希望能够检查给定目录中是否还有任何文件。如果是,我希望将它们上传到 Amazon S3,然后在本地删除。

让我知道如何进行此项检查。任何帮助深表感谢。

标签: pythonwindowsamazon-web-servicesamazon-s3boto3

解决方案


推荐阅读