Список всех ключей S3 между датой начала (включительно) и датой окончания (исключая) - PullRequest
0 голосов
/ 23 октября 2019

Есть ли способ перечислить все файлы s3 между указанными датами. Дата начала может быть передана в качестве префикса. У меня путаница относительно того, как пройти дату окончания. Пожалуйста, можете помочь.

import boto3


def get_matching_s3_objects(bucket, prefix=''):
    """
    Generate objects in an S3 bucket.

    :param bucket: Name of the S3 bucket.
    :param prefix: Only fetch objects whose key starts with
        this prefix
    """
    s3 = boto3.client('s3')
    kwargs = {'Bucket': bucket}

    if isinstance(prefix, str):
        kwargs['Prefix'] = prefix

    while True:

        # The S3 API response is a large blob of metadata.
        # 'Contents' contains information about the listed objects.
        resp = s3.list_objects_v2(**kwargs)

        try:
            contents = resp['Contents']
        except KeyError:
            return

        for obj in contents:
            key = obj['Key']
            if key.startswith(prefix) and key.endswith(suffix):
                yield obj

        # The S3 API is paginated, returning up to 1000 keys at a time.
        # Pass the continuation token into the next response, until we
        # reach the final page (when this field is missing).
        try:
            kwargs['ContinuationToken'] = resp['NextContinuationToken']
        except KeyError:
            break


def get_matching_s3_keys(bucket, prefix=''):
    """
    Generate the keys in an S3 bucket.

    :param bucket: Name of the S3 bucket.
    :param prefix: Only fetch keys that start with this prefix (optional).
    :param suffix: Only fetch keys that end with this suffix (optional).
    """
    for obj in get_matching_s3_objects(bucket, prefix, suffix):
        yield obj['Key']

1 Ответ

1 голос
/ 23 октября 2019

AFAIK, нет прямого способа фильтрации по дате с использованием boto3, единственный доступный фильтр : Bucket, Delimiter, EncodingType, Marker, MaxKeys, Prefixи RequestPayer.

Так что вам нужно циклически переключать ключи / объекты, чтобы сравнить дату начала / окончания с значением объекта last_modified datetime, чтобы получить все объекты в определенном сегменте за неделю назад(включено) и сегодня (исключено) я сделаю что-то вроде

from datetime import datetime, timedelta

import boto3
from pytz import UTC as utc

# NOTE: We need timezone aware objects, because the s3 object one will be.
today = utc.localize(datetime.utcnow())
since = today - timedelta(weeks=1)

# WARNINGS: 
# - You may need to provide proper credentials when calling boto3.resource...
# - Error management will need to be added, in case the bucket doesn't exist.
keys = [
    o for o in boto3.resource('s3').Bucket(name='some_bucket').objects.all()
    if o.last_modified < today and o.last_modified >= since
]
...