Archive for the 's3' Category

S3 demo using Django

I have been amazed at how reliable storage is these days with services like . The S3 doesn’t mention using python and django so I thought I’d implement the demo in django. It really is very simple to take advantage of S3 in your django apps, as Adrian shows .

Grab the S3 libary from .

My view looks like this:

BUCKET_NAME = 's3demo'

def upload_and_view(request):
    conn = S3.AWSAuthConnection('your access key', 'your secret key')

    if request.method == 'POST':
        post_data = request.POST.copy()
        filedata = post_data['uploaded_file']['content']
        filename = post_data['uploaded_file']['filename']
        content_type = mimetypes.guess_type(filename)[0]
        if not content_type:
            content_type = 'text/plain'

        conn.put(BUCKET_NAME, filename, S3.S3Object(filedata),
                    {'x-amz-acl': 'public-read', 'Content-Type': content_type})

    bucket = conn.list_bucket(BUCKET_NAME)
    bucket_entries = bucket.entries

    return render_to_response('s3demo/upload_and_view.html', {'entries': bucket_entries})

The template is a simple web form. bucket_entries contains a list of files in the S3 bucket. Since I’ve set the ACL to be public readable I can print a list of urls like so:

{% for entry in entries %}
<a href="{{ entry.key }}">{{ entry.key }}</a><br />
{% endfor %}

Great stuff!