[英]Delete all keys in a bucket of s3 which are three days old using python
如何使用python刪除三天前的S3存儲桶中的所有鍵?
S3 存儲桶內容如下:
mybucket001/backup/1566394660_21_08_2019_backup
mybucket001/backup/1566394660_20_08_2019_backup
mybucket001/backup/1566394660_19_08_2019_backup
mybucket001/backup/1566394660_18_08_2019_backup
我只需要保留最近兩天的數據。
這是我嘗試過的:
import boto
from boto.s3.key import Key
keyId='***'
sKeyId='***'
srcFileName="file name" #Name of the file to be deleted
bucketName="bucket name" #Name of the bucket, where the file resides
conn = boto.connect_s3(keyId,sKeyId) #Connect to S3
bucket = conn.get_bucket(bucketName) #Get the bucket object
k = Key(bucket,srcFileName) #Get the key of the given object
k.delete()
您可以簡單地將Amazon S3 對象生命周期管理配置為在 3 天后刪除對象,而不是通過代碼執行此操作。
這似乎是使用boto
和 S3 的一種有點奇怪的方式; 我會設置一個 S3 客戶端:
import boto3
import datetime
s3 = boto3.client('s3')
然后使用boto API 列出存儲桶中的文件(假設存儲桶存在):
files = s3.list_objects_v2(Bucket='my-bucket')['Contents']
這將為您提供一個字典列表,每個字典對應一個對象/文件。
然后,您可以按修改日期過濾此列表並提取密鑰:
old_files = [{'Key': file['Key']} for file in files if file['LastModified'] < datetime.now() - timedelta(days=2)]
然后再次使用 API刪除這些文件的特定部分:
s3.delete_objects(Bucket='my-bucket', Delete={'Objects': old_files})
嘗試這樣的事情:
import boto
from datetime import datetime
from boto.s3.key import Key
keyId='***'
sKeyId='***'
srcFileName="file name" #Name of the file to be deleted
bucketName="bucket name" #Name of the bucket, where the file resides
conn = boto.connect_s3(keyId,sKeyId) #Connect to S3
bucket = conn.get_bucket(bucketName) #Get the bucket object
k = Key(bucket,srcFileName) #Get the key of the given object
today = datetime.now().day # Get current day
if today - int(k.split('_')[1]) >= 2: # check the day difference for the last 2 days
k.delete()
為每個鍵運行
您完全不需要擔心刪除,因為 S3 本身會讓您頭疼。
參考https://aws.amazon.com/.../aws/amazon-s3-object-expiration/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.