Home > Blockchain >  How to copy a file from s3 into the same exact location?
How to copy a file from s3 into the same exact location?

Time:10-28

I have tried boto3 copy and copy_object methods but I keep getting this error.

Error I am getting:

botocore.exceptions.ClientError: An error occurred (InvalidRequest) when calling the CopyObject operation: This copy request is illegal because it is trying to copy an object to itself without changing the object’s metadata, storage class, website redirect location or encryption attributes.

Code I used

def copy(from_loc, to_loc):
    s3_b = boto3.client("s3")
    from_buc = to_loc["Bucket"]
    from_key = to_loc["Key"]
    to_buc = to_loc["Bucket"]
    to_key = to_loc["Key"]
    rsp=s3_b.copy_object(Bucket=to_buc, Key=to_key, CopySource=from_loc)
    print(rsp)

I am able to do this on the AWS UI but not through code. Clearly the solution is to change the objects metadata. But How would you change an objects metadata and paste it if the object I am changing is itself?

CodePudding user response:

You can specify some metadata, eg:

s3_client.copy_object(Bucket=BUCKET, Key=KEY, CopySource=SOURCE, Metadata={'foo':'bar'})

This will replace the existing metadata with foo/bar. If you wish to retain the existing metadata too, then you'll need to add it to the Metadata object. Basically, the Metadata needs to change, and that's good enough reason for copy_object() to permit copying an object to itself.

  • Related