如何使用Boto3库在Python中基于最后修改日期从S3中获取文件列表使用AWS资源?
问题陈述 − 使用Python中的boto3库根据给定的日期时间戳获取S3中的文件列表。
示例 − 如果Bucket_1/testfolder的test.zip文件在2021-01-21 13:19:56.986445+00:00之后被修改,那么请列出它。
更多Python相关文章,请阅读:Python 教程
解决此问题的方法/算法
步骤1 − 导入boto3和botocore异常处理。
步骤2 − s3_path 和 last_modified_timestamp 是函数 list_all_objects_based_on_last_modified 的两个参数。 “last_modified_timestamp” 应该是“2021-01-22 13:19:56.986445+00:00”格式。默认情况下,无论地理位置,boto3都理解UTC时区。
步骤3 − 验证s3_path格式是否为s3://bucket_name/key。
步骤4 − 使用boto3库创建AWS会话。
步骤5 − 为S3创建AWS资源。
步骤6 − 现在使用函数 list_objects 列出给定前缀的所有对象,并处理任何异常。
步骤7 − 上述函数的结果是一个字典,其中包含名为 ‘Contents’的键中的所有文件级信息。现在将桶级细节提取到对象中。
步骤8 − 现在,对象也是一个具有文件的所有详细信息的字典。现在,获取每个文件的 LastModified 细节并与给定的日期时间戳进行比较。
步骤9 − 如果 LastModified 大于给定的时间戳,则保留完整文件名,否则忽略它。
步骤10 − 返回那些在给定日期时间戳之后修改的文件列表。
示例
以下代码基于最后修改日期时间戳从AWS S3中获取文件列表 −
import boto3
from botocore.exceptions import ClientError
def list_all_objects_based_on_last_modified(s3_files_path,
last_modified_timestamp):
if 's3://' not in s3_files_path:
raise Exception('给定的路径不是有效的s3路径。')
session = boto3.session.Session()
s3_resource = session.resource('s3')
bucket_token = s3_files_path.split('/')
bucket = bucket_token[2]
folder_path = bucket_token[3:]
prefix = ""
for path in folder_path:
prefix = prefix + path + '/'
try:
result = s3_resource.meta.client.list_objects(Bucket=bucket, Prefix=prefix)
except ClientError as e:
raise Exception( "list_all_objects_based_on_last_modified函数出现boto3客户端错误: " + e.__str__())
except Exception as e:
raise Exception( "s3 helper的list_all_objects_based_on_last_modified函数中出现意外错误: " + e.__str__())
filtered_file_names = []
for obj in result['Contents']:
if str(obj["LastModified"]) >= str(last_modified_timestamp):
full_s3_file = "s3://" + bucket + "/" + obj["Key"]
filtered_file_names.append(full_s3_file)
return filtered_file_names
#give a timestamp to fetch test.zip
print(list_all_objects_based_on_last_modified("s3://Bucket_1/testfolder" , "2021-01-21 13:19:56.986445+00:00"))
#give a timestamp no file is modified after that
print(list_all_objects_based_on_last_modified("s3://Bucket_1/testfolder" , "2021-01-21 13:19:56.986445+00:00"))
输出
#给一个时间戳来获取test.zip
[s3://Bucket_1/testfolder/test.zip]
#给一个没有文件在该时间戳之后被修改的时间戳
[]
极客教程