In Boto 3, there is no method equivalent to ʻexists ()that confirms the existence of the key until the time of Boto 2. However, a similar function can be achieved by using
list_objects ()` as shown below.
exists.py
from boto3 import Session
s3client = Session().client('s3')
def exists(bucket: str, key: str) -> bool:
"""
Does the specified key exist in the specified bucket?
:param bucket: (str) bucket name
:param key: (str) key
:return: (bool)
"""
contents = s3client.list_objects(Prefix=key, Bucket=bucket).get("Contents")
if contents:
for content in contents:
if content.get("Key") == key:
return True
return False
list_objects ()
returns a hash of the form:
{
'IsTruncated': True|False, #Was the result shredded? True if done
'Marker': 'string',
'NextMarker': 'string',
'Contents': [
{
'Key': 'string',
'LastModified': datetime(2015, 1, 1),
'ETag': 'string',
'Size': 123,
'StorageClass': 'STANDARD'|'REDUCED_REDUNDANCY'|'GLACIER',
'Owner': {
'DisplayName': 'string',
'ID': 'string'
}
},
],
'Name': 'string',
'Prefix': 'string',
<Omitted>
}
'Contents'
is the key, and this is the array of corresponding keys. If there is no corresponding key, 'Contents'
will not be included in the return value. Therefore, check if 'Contents'
is included, and if the value of'Key'
in the dictionary in the list matches the key
given as an argument, it corresponds to ʻexists ()`. You can reproduce the function.
Full path of key to Prefix
? It feels a little strange to specify, but I understand that Prefix is such a thing.
In the following cases, it did not work properly, so I fixed it (thx, @masahiro_toriumi)
Prefix only specifies the prefix of the key, so for example, if you call list_object with Prefix "MyBucket / aaa.txt", it will also be caught in "MyBucket / aaa.txt.bak", so "MyBucket / I can't tell exactly if the key "aaa.txt" exists
Recommended Posts