leo leo - 5 months ago 208
Python Question

How do I set the Content-Type of an existing S3 key with boto3?

I want to update the Content-Type of an existing object in a S3 bucket, using boto3, but how do I do that, without having to re-upload the file?

file_object = s3.Object(bucket_name, key)
print file_object.content_type
# binary/octet-stream
file_object.content_type = 'application/pdf'
# AttributeError: can't set attribute


Is there a method for this I have missed in boto3?

Related questions:


leo leo
Answer

Thee doesn't seem to exist any method for this in boto3. However, it turnes out you can access the AWS low level API through boto3, and do like this:

s3 = resource('s3')
api_client = s3.meta.client
response = api_client.copy_object(Bucket=bucket_name,
                                  Key=key,
                                  ContentType='application/pdf',
                                  MetadataDirective="REPLACE",
                                  CopySource=bucket_name + "/" + key)

The MetadataDirective="REPLACE" turns out to be required for S3 to overwrite the file, otherwise you will get an error message saying This copy request is illegal because it is trying to copy an object to itself without changing the object's metadata, storage class, website redirect location or encryption attributes. .