django-cloudi /

from datetime import datetime
import sys
import boto
from boto.s3.key import Key
import mimetypes
import json

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 photo to upload')

def index(request):
    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 path
        k.set_contents_from_file(content, headers=settings.AWS_HEADERS) # this uploads the file
        # 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(), context_instance=RequestContext(request))

    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)


#f = boto.storage_uri('s3://happyherb-photos/2011/02/')