bgneal@697
|
1 """s3.py
|
bgneal@697
|
2
|
bgneal@697
|
3 This module provides the necessary S3 upload functionality for the user_photos
|
bgneal@697
|
4 application.
|
bgneal@697
|
5
|
bgneal@697
|
6 """
|
bgneal@697
|
7 from boto.s3.connection import S3Connection
|
bgneal@697
|
8 from boto.s3.key import Key
|
bgneal@697
|
9
|
bgneal@697
|
10
|
bgneal@697
|
11 class S3Bucket(object):
|
bgneal@697
|
12 """This class abstracts an Amazon S3 bucket.
|
bgneal@697
|
13
|
bgneal@697
|
14 We currently only need upload functionality.
|
bgneal@697
|
15
|
bgneal@697
|
16 """
|
bgneal@697
|
17 def __init__(self, access_key, secret_key, bucket_name):
|
bgneal@697
|
18 self.conn = S3Connection(access_key, secret_key)
|
bgneal@697
|
19 self.bucket = self.conn.get_bucket(bucket_name, validate=False)
|
bgneal@697
|
20
|
bgneal@697
|
21 def upload_from_filename(self, key_name, filename, metadata=None,
|
bgneal@697
|
22 public=True):
|
bgneal@697
|
23 """Uploads data from the file named by filename to a new key named
|
bgneal@697
|
24 key_name. metadata, if not None, must be a dict of metadata key / value
|
bgneal@697
|
25 pairs which will be added to the key.
|
bgneal@697
|
26
|
bgneal@697
|
27 If public is True, the key will be made public after the upload.
|
bgneal@697
|
28
|
bgneal@697
|
29 """
|
bgneal@697
|
30 key = self._make_key(key_name, metadata)
|
bgneal@697
|
31 key.set_contents_from_filename(filename)
|
bgneal@697
|
32 if public:
|
bgneal@697
|
33 key.make_public()
|
bgneal@697
|
34
|
bgneal@697
|
35 def upload_from_string(self, key_name, content, metadata=None,
|
bgneal@697
|
36 public=True):
|
bgneal@697
|
37 """Creates a new key with the given key_name, and uploads the string
|
bgneal@697
|
38 content to it. metadata, if not None, must be a dict of metadata key /
|
bgneal@697
|
39 value pairs which will be added to the key.
|
bgneal@697
|
40
|
bgneal@697
|
41 If public is True, the key will be made public after the upload.
|
bgneal@697
|
42
|
bgneal@697
|
43 """
|
bgneal@697
|
44 key = self._make_key(key_name, metadata)
|
bgneal@697
|
45 key.set_contents_from_string(content)
|
bgneal@697
|
46 if public:
|
bgneal@697
|
47 key.make_public()
|
bgneal@697
|
48
|
bgneal@697
|
49 def _make_key(self, key_name, metadata):
|
bgneal@697
|
50 """Private method to create a key and optionally apply metadata to
|
bgneal@697
|
51 it.
|
bgneal@697
|
52
|
bgneal@697
|
53 """
|
bgneal@697
|
54 key = Key(self.bucket)
|
bgneal@697
|
55 key.key = key_name
|
bgneal@697
|
56 if metadata:
|
bgneal@697
|
57 for k, v in metadata.iteritems():
|
bgneal@697
|
58 key.set_metadata(k, v)
|
bgneal@697
|
59 return key
|