Source Guru

Django – S3 Storage Engine

by on Dec.02, 2008, under Personal

After having read James Bennett‘s article on Django Media and Performance I decided that I wanted to be using S3 for storing and serving media for a new site that I’m working on (in Django)

So, it seems that it’s not that easy. I did first of all experiment with using FUSE, but decided against it.

Anyway, looking through some obscure documentation, I found that Django can use custom storage methods. So, I thought I’d write one.

You can find the file here

The code requires you to have Amazon’s S3 API installed.

So, how do you use it? It’s pretty simple really. First of all – you need to setup your configuration – so edit settings.py and add the following (changing the values to suit your needs!)

S3_SETTINGS = {
    'aws_key': 'XXXXXXXXXXXXXXXXXXXX',
    'aws_secret_key': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    'bucket': 'bucket_name',
    'default_perm': 'public-read',
    'vanity_url': False
}

The settings should be self-explanatory – apart from ‘vanity_url’. S3 allows you to CNAME a domain name to a bucket with a similar name – for example, I could CNAME files.sourceguru.net to files.sourceguru.net.s3.amazonaws.com and it would allow me to serve information from that bucket as if they were coming from my own domain. (infact, I’m tempted to do this – I’ve too much stuff in my files section!) – the vanity_url – when set to True – will use the bucketname as the domain instead of <bucketname>.s3.amazonaws.com.

Now, to use it in a model, it’s as simple as adding an import line at the top of the models file

from site.app.s3storage import S3Storage

and then, in your model

class Item(models.Model):
    storage = S3Storage()
    image = models.ImageField(upload_to='path', storage=storage)

Pretty simple, :D

Hope this helps some people out there!

:, , , , ,

5 Comments for this entry

1 Trackback or Pingback for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!