"""S3 module.""" import boto3 from botocore.exceptions import ClientError from asset_transcoder.utils import exceptions client = boto3.client('s3') resource = boto3.resource('s3') def update_file_metadata(key, bucket, metadata): """Update a file's metadata using the REPLACE directive. Args: key (str): filename with the extension bucket (str): bucket metadata (dict): key / value pairs to be merged with the file's existing metadata """ try: response = client.head_object( Bucket=bucket, Key=key ) asset_metadata = { 'ContentType': response['ContentType'], 'Metadata': response['Metadata'], 'MetadataDirective': 'REPLACE' } asset_metadata.update(metadata) if 'Metadata' in metadata: asset_metadata['Metadata'].update(response['Metadata']) copy_source = { 'Bucket': bucket, 'Key': key } resource.meta.client.copy( copy_source, bucket, key, ExtraArgs=asset_metadata, SourceClient=client ) except ClientError as e: error_message = 'error updating metadata for {key} in bucket {bucket}'.format(key=key, bucket=bucket) raise exceptions.OwsError.from_boto3_client_error(e, error_message)