django-cloudi /

from datetime import datetime
import sys
import mimetypes
import json

import boto
from boto.s3.key import Key
from django import forms
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext

class UploadForm(forms.Form):
    file = forms.ImageField(label='Select a photo to upload')

def index(request):
    '''  This view displays a single field form to upload your image to S3. It
         also sets the mimetype, sets the acl to read-only for public, and
         specifics the upload path based on the current year and month.

         S3 bucket name, keys, and content headers are specificed in the settings

         After the upload completes it returns json with the image url.
         Javascript adds that value to form field that the CloudImages widget
         is bound.
    def store_in_s3(filename, content):
        c = boto.connect_s3(settings.AWS_ACCESS_KEY_ID,
                            settings.AWS_SECRET_ACCESS_KEY) # authenticate
        b = c.get_bucket(settings.AWS_STORAGE_BUCKET_NAME) # connect to the bucket
        k = Key(b)
        t = # get date for storage path
        month = t.strftime('%m')
        year = t.strftime('%Y')
        k.key = '%s/%s/%s' % (year, month, filename) #set the upload path
        # This uploads the file to S3.
        k.set_contents_from_file(content, headers=settings.AWS_HEADERS) 
        # Mime must be set or files will download instead of
        # displaying in the browser.
        mime = mimetypes.guess_type(filename)[0]
        k.set_metadata("Content-Type", mime)
        global url
        url = "%s/%s" % (settings.AWS_URL, k.key)

    if not request.method == "POST":
        form = UploadForm()
        return render_to_response("cloud_form.html", locals(),

    if request.method == "POST":
        form = UploadForm(request.POST, request.FILES)
	if not form.is_valid():
		return render_to_response("cloud_form.html", {"form":form})
	    file = request.FILES["file"]
	    filename =
            content = file
	    store_in_s3(filename, content)
            urljson = json.dumps(url)
        except IOError, e:
            print e

	return HttpResponse(urljson)