Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using boto, set content_type on files which are already present on s3

I'm using django storages with the s3boto backend. As per this issue, http://code.larlet.fr/django-storages/issue/5/s3botostorage-set-content-type-header-acl-fixed-use-http-and-disable-query-auth-by I have a bunch of files (all of them) that have content type 'application/octet-stream'. Given that I have an instance of <class 'boto.s3.key.Key'>, how can I set the content_type?

In [29]: a.file.file.key.content_type
Out[29]: 'application/octet-stream'

In [30]: mimetypes.guess_type(a.file.file.key.name)[0]
Out[30]: 'image/jpeg'

In [31]: type(a.file.file.key)
Out[31]: <class 'boto.s3.key.Key'>
like image 763
Skylar Saveland Avatar asked Feb 10 '12 16:02

Skylar Saveland


People also ask

Does Put_object overwrite?

If an object already exists in a bucket, the new object will overwrite it because Amazon S3 stores the last write request.

What is boto3 client (' S3 ')?

​Boto3 is the official AWS SDK for Python, used to create, configure, and manage AWS services. The following are examples of defining a resource/client in boto3 for the Weka S3 service, managing credentials, and pre-signed URLs, generating secure temporary tokens, and using those to run S3 API calls.


1 Answers

There is no way to modify the content type (or any other metadata) associated with a file after it has been created. You can, however, copy the file on the server side and modify the metadata in the process. Here is a gist on github that should help:

https://gist.github.com/1791086

Contents:

import boto

s3 = boto.connect_s3()
bucket = s3.lookup('mybucket')
key = bucket.lookup('mykey')

# Copy the key onto itself, preserving the ACL but changing the content-type
key.copy(key.bucket, key.name, preserve_acl=True,
    metadata={'Content-Type': 'text/plain'})

key = bucket.lookup('mykey')
print key.content_type

Mitch

like image 100
garnaat Avatar answered Sep 21 '22 23:09

garnaat