"""Amazon S3 connector.""" import boto from boto.exception import S3ResponseError from oto import response from label_copy_export import config from label_copy_export.connectors.sentry import sentry_client from label_copy_export.constants import s3 def upload_file_to_s3(filename, s3_filename, metadata=None): """Connect to S3, get bucket from config and upload file there. Args: filename (str): absolute path to file which should be uploaded to s3. s3_filename (str): Name which uploaded file will have in bucket. metadata (dict): additional metadata for key in s3. Returns: (Response): Response with errors if not valid or empty if valid. """ try: s3_connection = boto.connect_s3() bucket_name, file_path = config.S3_BUCKET_PATH.split('/', maxsplit=1) s3_key_name = '{path}/{filename}'.format( path=file_path, filename=s3_filename) bucket = s3_connection.get_bucket(bucket_name) if not metadata: metadata = { s3.CONTENT_DISPOSITION: s3.ATTACHMENT} else: metadata[s3.CONTENT_DISPOSITION] = s3.ATTACHMENT key = bucket.new_key(s3_key_name) key.metadata = metadata key.set_contents_from_filename(filename) return response.Response() except S3ResponseError as ex: if sentry_client: sentry_client.captureException() return response.create_error_response( code=ex.error_code, message=ex.message, status=ex.status) except FileNotFoundError: return response.create_fatal_response( '{csv} file doesn\'t exist'.format(csv=filename))