Search code examples
pythondjangoamazon-s3django-modelsboto3

How to get last modified date with each image present in different folders in AWS S3 bucket


I have created a bucket on aws s3 storage and saving folders dynamically by the user in that bucket. The code is working perfectly and getting each folder images. But I am not able to get last modified date of each image present in different folders.

I want to get last modified date of each image present in different folders.

#views.py code:
def home(request):
    data = {}
    storage = S3Boto3Storage()
    s3 = boto3.client('s3')

    image_info_list = {}

    for obj in s3.list_objects(Bucket=storage.bucket_name)['Contents']:
        # Getting the folder name from the object key.
        folder_name = obj['Key'].split('/', 1)[0]

        if folder_name not in image_info_list:
            image_info_list[folder_name] = []

        # Adding the image url to the folder's image list.
        image_info_list[folder_name].append(storage.url(obj['Key']))

        # Check if a Camera instance with the same name already exists
        camera, created = Camera.objects.get_or_create(name=folder_name)

    data = {
        'image_info_list': image_info_list,
        'cameras': cameras,
    }
    return render(request, 'index.html', data)

Solution

  • Access the LastModified attribute for the object i.e.

    for obj in s3.list_objects(Bucket=storage.bucket_name)['Contents']:
            last_modified = obj['LastModified']