check if a key exists in a bucket in s3 using boto3

前端 未结 24 2889
花落未央
花落未央 2020-11-28 19:03

I would like to know if a key exists in boto3. I can loop the bucket contents and check the key if it matches.

But that seems longer and an overkill. Boto3 official

24条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 19:25

    Boto 2's boto.s3.key.Key object used to have an exists method that checked if the key existed on S3 by doing a HEAD request and looking at the the result, but it seems that that no longer exists. You have to do it yourself:

    import boto3
    import botocore
    
    s3 = boto3.resource('s3')
    
    try:
        s3.Object('my-bucket', 'dootdoot.jpg').load()
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == "404":
            # The object does not exist.
            ...
        else:
            # Something else has gone wrong.
            raise
    else:
        # The object does exist.
        ...
    

    load() does a HEAD request for a single key, which is fast, even if the object in question is large or you have many objects in your bucket.

    Of course, you might be checking if the object exists because you're planning on using it. If that is the case, you can just forget about the load() and do a get() or download_file() directly, then handle the error case there.

提交回复
热议问题