Source

django-cloudi / views.py

Full commit
from datetime import datetime
import sys
import mimetypes

try:
    import json
except ImportError:
    import simplejson as 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
from django.contrib.auth.decorators import login_required

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

@login_required    
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
         file.

         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 = datetime.now() # 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) 
        k.set_acl('public-read')
        # 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("cloudi_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("cloudi_form.html", {"form":form})
	try:
	    file = request.FILES["file"]
	    filename = file.name
            content = file
	    store_in_s3(filename, content)

        except IOError, e:
            print e

	return HttpResponse(url)