Total Complexity | 5 |
Total Lines | 37 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | import os |
||
15 | class UploadToS3(St2BaseAction): |
||
16 | """ |
||
17 | Note: The destination bucket must be configured so everyone can write to it, |
||
18 | but only we can read from it. |
||
19 | """ |
||
20 | |||
21 | def run(self, bucket, file_name, remote_file=None): |
||
22 | if not remote_file: |
||
23 | remote_file = os.path.basename(file_name) |
||
24 | |||
25 | if not os.path.isfile(file_name): |
||
26 | raise ValueError('Local file "%s" doesn\'t exist' % (file_name)) |
||
27 | |||
28 | url = S3_BUCKET_URL % {'bucket': bucket} |
||
29 | url = url + remote_file |
||
30 | |||
31 | # Note: Requests library performs streaming and chunked upload |
||
32 | files = {'file': open(file_name, 'rb')} |
||
33 | response = requests.put(url=url, files=files) |
||
34 | |||
35 | if response.status_code in [httplib.OK, httplib.CREATED]: |
||
36 | status = 'ok' |
||
37 | error = None |
||
38 | else: |
||
39 | status = 'failure' |
||
40 | error = response.text |
||
41 | |||
42 | result = { |
||
43 | 'status_code': response.status_code, |
||
44 | 'status': status, |
||
45 | 'uploaded_file': remote_file, |
||
46 | } |
||
47 | |||
48 | if error: |
||
49 | result['error'] = error |
||
50 | |||
51 | return result |
||
52 |