comparison user_photos/s3.py @ 697:67f8d49a9377

Cleaned up the code a bit. Separated the S3 stuff out into its own class. This class maybe should be in core. Still want to do some kind of context manager around the temporary file we are creating to ensure it gets deleted.
author Brian Neal <bgneal@gmail.com>
date Sun, 08 Sep 2013 21:02:58 -0500
parents
children
comparison
equal deleted inserted replaced
696:b2a8fde3173a 697:67f8d49a9377
1 """s3.py
2
3 This module provides the necessary S3 upload functionality for the user_photos
4 application.
5
6 """
7 from boto.s3.connection import S3Connection
8 from boto.s3.key import Key
9
10
11 class S3Bucket(object):
12 """This class abstracts an Amazon S3 bucket.
13
14 We currently only need upload functionality.
15
16 """
17 def __init__(self, access_key, secret_key, bucket_name):
18 self.conn = S3Connection(access_key, secret_key)
19 self.bucket = self.conn.get_bucket(bucket_name, validate=False)
20
21 def upload_from_filename(self, key_name, filename, metadata=None,
22 public=True):
23 """Uploads data from the file named by filename to a new key named
24 key_name. metadata, if not None, must be a dict of metadata key / value
25 pairs which will be added to the key.
26
27 If public is True, the key will be made public after the upload.
28
29 """
30 key = self._make_key(key_name, metadata)
31 key.set_contents_from_filename(filename)
32 if public:
33 key.make_public()
34
35 def upload_from_string(self, key_name, content, metadata=None,
36 public=True):
37 """Creates a new key with the given key_name, and uploads the string
38 content to it. metadata, if not None, must be a dict of metadata key /
39 value pairs which will be added to the key.
40
41 If public is True, the key will be made public after the upload.
42
43 """
44 key = self._make_key(key_name, metadata)
45 key.set_contents_from_string(content)
46 if public:
47 key.make_public()
48
49 def _make_key(self, key_name, metadata):
50 """Private method to create a key and optionally apply metadata to
51 it.
52
53 """
54 key = Key(self.bucket)
55 key.key = key_name
56 if metadata:
57 for k, v in metadata.iteritems():
58 key.set_metadata(k, v)
59 return key