S3 giving me NoSuchKey error even when the key exi

2020-07-03 06:56发布

问题:

This is my boto3 command for getting the object with a specific key from an S3 bucket:

resp = s3client.get_object(Bucket='<>-<>', Key='MzA1MjY1NzkzX2QudHh0')

It gives the following error:

botocore.errorfactory.NoSuchKey: An error occurred (NoSuchKey) when calling the GetObject operation: The specified key does not exist.

I have checked in the bucket, and the key actually exists

Did I miss something or did I do something wrong here?

回答1:

You have a %0A at the end of your URL; that's a line separator.



回答2:

Since you know the key that you have is definitely in the name of the file you are looking for, I recommend using a filter to get objects with names with your key as their prefix.

s3 = boto3.resource('s3')
bucket = s3.Bucket('cypher-secondarybucket')
for obj in bucket.objects.filter(Prefix='MzA1MjY1NzkzX2QudHh0'):
    print obj.key

When you run this code, you will get the key names of all the files that start with your key. This will help you find out what your file is exactly called on S3.



回答3:

Another possible issue that I came across that was causing a line separator in my url for an object was that in one of AWS documentation for getting the key of an object shows this code as an example to get the key of an object.

foreach ($results as $result) {
    foreach ($result['Contents'] as $object) {
        echo $object['Key'] . PHP_EOL;
    }
}

The problem is the PHP_EOL at the end. Just remove it and the line separator goes away.

$object['Key'] . PHP_EOL; --> $object['Key'];