Python‎ > ‎

Boto Python script to add "Cache-Control" header for AWS S3 Bucket

posted Sep 16, 2014, 5:31 PM by Chris G
This script uses Boto, the Amazon AWS library for Python. The purpose of this script is to add the "Cache-Control" header to all .png and .jpg images that are already present in your web-enabled S3 Bucket. It also assumes that these files are publicly available.

This setting will improve the performance and rating of your website by telling the client's browsers that they do not need to request those files every time, but instead pull them from the browser's cache.
.
from boto.s3.connection import S3Connection

conn = S3Connection('YOUR_KEY', 'YOUR_KEY')

from boto.s3.key import Key

extensions = ['.jpg', '.png']

AWS_HEADERS = {
    'Cache-Control': 'max-age=31556926,public'
}
AWS_ACL = 'public-read'



bucket = conn.get_bucket('<your bucket name>')
for key in bucket:
    keyString = str(key.key)
    extension = os.path.splitext(keyString)[1]
    if extension in extensions:
        print key.name
        if key.name.endswith('.jpg'):
            contentType = 'image/jpeg'
        elif key.name.endswith('.png'):
            contentType = 'image/png'
        else:
            continue

        key.metadata.update({
        'Content-Type': contentType,
        'Cache-Control': 'max-age=864000'
        })
        key.copy(
            key.bucket.name,
            key.name,
            key.metadata,
            preserve_acl=True
        )



Comments