【问题标题】:How to retrieve only the last_modified key in S3 with boto3如何使用 boto3 仅检索 S3 中的 last_modified 键
【发布时间】:2018-12-28 14:29:50
【问题描述】:

我只想从我的 S3 存储桶中检索 last_modified 键,使用 boto3 在特定前缀中。

# Get Today's date
today = datetime.date.today()

# Get Objects date
s3 = boto3.resource('s3',region_name=AWS_REGION)
bucket = s3.Bucket('xxx')
objs = bucket.objects.filter(Prefix='yyyy').limit(1)

def get_object_check_alarm():
  try:
    for obj in objs:
        print(obj)
        lastobjectdate = (obj.last_modified).date()
  except botocore.exceptions.ClientError as e:
    error_code = e.response['Error']['Code']
    if error_code == '404':
        print("There is no file")

  # Compare with defined date
  if today == lastobjectdate:
    print(today)
    print(lastobjectdate)
    print("OK, lastest file comes from today")
  else:
    print(today)
    print(lastobjectdate)
    print("Mail sent")

使用此代码,当前结果不会输出最后修改的键。我尝试将limit() 增加到limit(10),但没有成功。

【问题讨论】:

  • 我只看到你打印出 obj 本身,从来没有在 lastobjectdate 上。此外,如果您完全没有打印出来,这意味着您的 objs 实际上是空列表。检查您的前缀。
  • 对不起,我已经添加了我的代码的缺失部分,这样会更容易理解

标签: python amazon-web-services amazon-s3 boto3


【解决方案1】:

--更新开始--

或许,在 S3 中创建带有日期前缀的对象可能会更好。

{bucket}/yyyy/mm/dd/{object}

示例:myS3bucket/2018/12/29/myfile.txt

使用这种方法,您的查询变得很简单,可以轻松找出您是否有当天的任何文件,而且您检索的文件数量列表也会变短。

prefix="/"+str(today.year)+"/"+str(today.month)+"/"+str(today.day)+"/"
objs = bucket.objects.filter(Prefix=prefix).all()

--更新完成--

我不确定你是否给出了完整的代码,但上面的 sn-p 中有一些缩进问题。我刚刚在下面进行了测试,它工作正常,我得到了正确的last_modified 日期。

请确保您作为存储桶位于正确的区域。 last_modified 也在 UTC 时区,所以你的比较应该考虑到这一点。

import boto3
from datetime import date
import botocore

# Get Today's date
today = date.today()
# Get Objects date
s3 = boto3.resource('s3',region_name='us-east-1')
bucket = s3.Bucket('xxxx')
prefix="/"+str(today.year)+"/"+str(today.month)+"/"+str(today.day)+"/"
objs = bucket.objects.filter(Prefix=prefix).all()

def get_object_check_alarm():
    try:
        for obj in objs:
            print(obj)
            lastobjectdate = (obj.last_modified).date()
    except botocore.exceptions.ClientError as e:
        error_code = e.response['Error']['Code']
        if error_code == '404':
            print("There is no file")

# Compare with defined date
    if today == lastobjectdate:
        print(today)
        print(lastobjectdate)
        print("OK, lastest file comes from today")
    else:
        print(today)
        print(lastobjectdate)
        print("Mail sent")

get_object_check_alarm()

下面是输出。我在 EST 区域,所以日期仍然是 12/28,但对象创建日期是 12/29,因为在创建对象时它已经是 12/29 在 UTC 区域。

s3.ObjectSummary(bucket_name='xxxx', key='yyyy/')

2018-12-28

2018-12-29

已发送邮件

【讨论】:

  • 如果我使用效果更好:objs = bucket.objects.filter(Prefix='prefix').all()
  • 是的。它与 all() 一起工作得更好。此外,我用在 S3 中创建对象的最佳实践方法更新了我的答案。我知道您正在寻找 last_modified ,因此如果您更新相同的文件,则仅修改日期会更改为旧日期前缀。只是想给你一些想法。
猜你喜欢
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 2021-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多