AWS boto3 + S3 + Lambda auto add cache control

For AWS Lambda with python, we need to use boto3. So a different code is required.

from __future__ import print_function

import json
import urllib
import boto3
import email
import time
from datetime import datetime, timedelta

s3 = boto3.resource('s3')
one_month = 3600*24*30
one_year  = 3600*24*365

def lambda_handler(event, context):
    # Get the object from the event and show its content type
    bucket_name = event['Records'][0]['s3']['bucket']['name']
    key_name = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')
    
    print(key_name)
    cache_time = one_month # or one_year
    #get the object
    object = s3.Object(bucket_name, key_name)
    
    #get object details 
    response = object.get() 
    # check if 'CacheControl' exists
    if 'CacheControl' in response:
        print("exists")
        return
    modified = response
    modified['Body'] = response['Body'].read()
    modified.pop("VersionId", None)
    modified.pop("AcceptRanges", None)
    modified.pop("ETag", None)
    modified.pop("LastModified", None)
    modified.pop("ResponseMetadata", None)
    modified['Metadata'] = response['Metadata']
    modified['CacheControl'] = ('max-age=%d, public' % (cache_time))
    # put the same object with a new CacheControl
    response = object.put(**modified)
    return

Leave a Reply

Your email address will not be published. Required fields are marked *