Package madrona :: Package common :: Module s3
[hide private]

Source Code for Module madrona.common.s3

 1  """ 
 2  Lingcod's custom S3 wrapper 
 3  Provides some useful shortcuts to working with commom AWS S3 tasks 
 4  """ 
 5  from mimetypes import guess_type 
 6  from boto.s3.connection import S3Connection 
 7  from boto.s3.key import Key 
 8  from django.conf import settings 
 9  import os 
10   
11 -def s3_bucket(bucket=None):
12 """ 13 Shortcut to a boto s3 bucket 14 Uses settings.ACCESS_KEY, settings.AWS_SECRET_KEY 15 defaults to settings.AWS_MEDIA_BUCKET 16 """ 17 conn = S3Connection(settings.AWS_ACCESS_KEY, settings.AWS_SECRET_KEY) 18 if not bucket: 19 try: 20 bucket = settings.AWS_MEDIA_BUCKET 21 except: 22 raise Exception("No bucket specified and no settings.AWS_MEDIA_BUCKET") 23 24 return conn.create_bucket(bucket)
25 26
27 -def get_s3_url(b,k):
28 """ 29 Returns the standard s3 url 30 """ 31 return 'http://%s.s3.amazonaws.com/%s' % (b.name, k.key)
32
33 -def upload_to_s3(local_path, keyname, mimetype=None, bucket=None, acl='public-read'):
34 """ 35 Given a local filepath, bucket name and keyname (the new s3 filename), 36 this function will connect, guess the mimetype of the file, upload the contents and set the acl. 37 Defaults to public-read 38 """ 39 b = s3_bucket(bucket) 40 41 if not os.path.exists(local_path): 42 raise Exception("%s does not exist; can't upload to S3" % local_path) 43 44 if not mimetype: 45 mimetype = guess_type(local_path)[0] 46 if not mimetype: 47 mimetype = "text/plain" 48 49 k = Key(b) 50 k.key = keyname 51 k.set_metadata("Content-Type", mimetype) 52 k.set_contents_from_filename(local_path) 53 k.set_acl(acl) 54 55 return get_s3_url(b,k)
56