comparison core/s3.py @ 700:e888d627928f

Refactored the processing of image uploads. I suspect I will use this general algorithm in other places (like POTD), so I made it reusable.
author Brian Neal <bgneal@gmail.com>
date Wed, 11 Sep 2013 20:31:23 -0500
parents user_photos/s3.py@67f8d49a9377
children bf5340705d0c
comparison
equal deleted inserted replaced
699:d33bedc3be74 700:e888d627928f
1 """s3.py
2
3 This module provides Amazon S3 convenience wrappers.
4
5 """
6 from boto.s3.connection import S3Connection
7 from boto.s3.key import Key
8
9
10 class S3Bucket(object):
11 """This class abstracts an Amazon S3 bucket.
12
13 We currently only support upload functionality.
14
15 """
16 def __init__(self, access_key, secret_key, base_url, bucket_name):
17 self.conn = S3Connection(access_key, secret_key)
18 self.bucket = self.conn.get_bucket(bucket_name, validate=False)
19 self.base_url = base_url
20 if not base_url.endswith('/'):
21 self.base_url += '/'
22 self.name = bucket_name
23
24 def upload_from_file(self, key_name, fp, metadata=None, public=True):
25 """Uploads data from the file object fp to a new key named
26 key_name. metadata, if not None, must be a dict of metadata key / value
27 pairs which will be added to the key.
28
29 If public is True, the key will be made public after the upload.
30
31 Returns the URL to the uploaded file.
32
33 """
34 key = self._make_key(key_name, metadata)
35 key.set_contents_from_file(fp)
36 if public:
37 key.make_public()
38 return '{}{}/{}'.format(self.base_url, self.name, key_name)
39
40 def upload_from_filename(self, key_name, filename, metadata=None,
41 public=True):
42 """Uploads data from the file named by filename to a new key named
43 key_name. metadata, if not None, must be a dict of metadata key / value
44 pairs which will be added to the key.
45
46 If public is True, the key will be made public after the upload.
47
48 Returns the URL to the uploaded file.
49
50 """
51 key = self._make_key(key_name, metadata)
52 key.set_contents_from_filename(filename)
53 if public:
54 key.make_public()
55 return '{}{}/{}'.format(self.base_url, self.name, key_name)
56
57 def upload_from_string(self, key_name, content, metadata=None,
58 public=True):
59 """Creates a new key with the given key_name, and uploads the string
60 content to it. metadata, if not None, must be a dict of metadata key /
61 value pairs which will be added to the key.
62
63 If public is True, the key will be made public after the upload.
64
65 Returns the URL to the uploaded file.
66
67 """
68 key = self._make_key(key_name, metadata)
69 key.set_contents_from_string(content)
70 if public:
71 key.make_public()
72 return '{}{}/{}'.format(self.base_url, self.name, key_name)
73
74 def _make_key(self, key_name, metadata):
75 """Private method to create a key and optionally apply metadata to
76 it.
77
78 """
79 key = Key(self.bucket)
80 key.key = key_name
81 if metadata:
82 for k, v in metadata.iteritems():
83 key.set_metadata(k, v)
84 return key