2016-02-02 22:26:49 +00:00
|
|
|
import botocore
|
2016-01-13 17:32:40 +00:00
|
|
|
from boto3 import resource
|
|
|
|
|
|
|
|
|
|
|
2016-02-05 16:13:06 +00:00
|
|
|
BUCKET_NAME = 'service-{}-notify'
|
|
|
|
|
|
|
|
|
|
|
2016-02-02 22:26:49 +00:00
|
|
|
def s3upload(upload_id, service_id, filedata, region):
|
2016-01-13 17:32:40 +00:00
|
|
|
s3 = resource('s3')
|
2016-02-05 16:13:06 +00:00
|
|
|
bucket_name = BUCKET_NAME.format(service_id)
|
2016-01-14 16:00:13 +00:00
|
|
|
contents = '\n'.join(filedata['data'])
|
2016-02-02 22:26:49 +00:00
|
|
|
|
|
|
|
|
exists = True
|
|
|
|
|
try:
|
|
|
|
|
s3.meta.client.head_bucket(Bucket=bucket_name)
|
|
|
|
|
except botocore.exceptions.ClientError as e:
|
|
|
|
|
error_code = int(e.response['Error']['Code'])
|
|
|
|
|
if error_code == 404:
|
|
|
|
|
exists = False
|
|
|
|
|
|
|
|
|
|
if not exists:
|
|
|
|
|
s3.create_bucket(Bucket=bucket_name,
|
|
|
|
|
CreateBucketConfiguration={'LocationConstraint': region})
|
|
|
|
|
|
2016-02-04 12:06:06 +00:00
|
|
|
upload_file_name = "{}.csv".format(upload_id)
|
|
|
|
|
key = s3.Object(bucket_name, upload_file_name)
|
2016-01-14 16:00:13 +00:00
|
|
|
key.put(Body=contents, ServerSideEncryption='AES256')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def s3download(service_id, upload_id):
|
2016-02-05 16:13:06 +00:00
|
|
|
contents = ''
|
|
|
|
|
try:
|
|
|
|
|
s3 = resource('s3')
|
|
|
|
|
bucket_name = BUCKET_NAME.format(service_id)
|
|
|
|
|
upload_file_name = "{}.csv".format(upload_id)
|
|
|
|
|
key = s3.Object(bucket_name, upload_file_name)
|
|
|
|
|
contents = key.get()['Body'].read().decode('utf-8')
|
|
|
|
|
except botocore.exceptions.ClientError as e:
|
|
|
|
|
err = e.response['Error']
|
|
|
|
|
if err['Code'] == 'NoSuchBucket':
|
|
|
|
|
err_msg = '{}:{}'.format(err['BucketName'], err['Message'])
|
|
|
|
|
# TODO properly log error
|
|
|
|
|
print(err_msg)
|
2016-01-14 16:00:13 +00:00
|
|
|
return contents
|