如何使用Python中的Boto3庫,基於AWS資源和最後修改日期獲取S3檔案列表?


問題陳述 − 使用Python中的boto3庫獲取S3中的檔案列表,這些檔案是在給定日期時間戳之後修改的。

示例 − 如果在2021-01-21 13:19:56.986445+00:00之後修改了Bucket_1/testfolder中的test.zip,則列出它。

解決此問題的方法/演算法

步驟1 − 匯入boto3和botocore異常以處理異常。

步驟2s3_pathlast_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是否以AWS格式(s3://bucket_name/key)傳遞。

步驟4 − 使用boto3庫建立一個AWS會話。

步驟5 − 為S3建立一個AWS資源。

步驟6 − 現在使用list_objects函式列出給定字首的所有物件,並處理任何異常。

步驟7 − 上述函式的結果是一個字典,它在名為“Contents”的鍵中包含所有檔案級資訊。現在將桶級詳細資訊提取到一個物件中。

步驟8 − 現在,object也是一個字典,包含檔案的全部詳細資訊。現在,獲取每個檔案的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('Given path is not a valid s3 path.')
   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( "boto3 client error in list_all_objects_based_on_last_modified function: " + e.__str__())
   except Exception as e:
      raise Exception( "Unexpected error in list_all_objects_based_on_last_modified
function of s3 helper: " + 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"))

輸出

#give a timestamp to fetch test.zip
[s3://Bucket_1/testfolder/test.zip]
#give a timestamp no file is modified after that
[]

更新於:2021年3月22日

8K+ 次檢視

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.