Accessing a specific key in a s3 bucket using boto3

て烟熏妆下的殇ゞ 提交于 2020-01-06 04:41:18

问题


I am trying to access a specific object in my s3 bucket using boto3 for deletion.

the code below is from the boto3 documentation. https://boto3.readthedocs.io/en/latest/guide/migrations3.html#accessing-a-bucket

# Boto 3
for key in bucket.objects.all():
    key.delete()

great but i would much rather have a dictionary reference then iterating though objects. That isn't the greatest at scaling.

Is there a way to grab an object using its key?

edit:

I attempted this but it didnt work. Looking through the objects collection manager.

s3 = boto3.resource('s3')
bucket = s3.Bucket(AWS_UPLOAD_BUCKET)
key = bucket.objects.get(key = venueobjects3key)

回答1:


looks like this isn't possible. Here is the filtering code. its easier for me to just to iterate through the keys and find the one I want. Lame.

Filtering Some collections support extra arguments to filter the returned data set, which are passed into the underlying service operation. Use the filter() method to filter the results:

# S3 list all keys with the prefix 'photos/'
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
    for obj in bucket.objects.filter(Prefix='photos/'):
        print('{0}:{1}'.format(bucket.name, obj.key))



回答2:


use the below code I think it will help you

S3 = boto3.client(
    's3',
    region_name = 'us-west-2',
    aws_access_key_id = AWS_ACCESS_KEY_ID,
    aws_secret_access_key = AWS_SECRET_ACCESS_KEY
)
#Create a file object using the bucket and object key. 
fileobj = S3.get_object(
    Bucket=<Bucket_Name>,
    Key=<Key_Name>
    ) 
# open the file object and read it into the variable filedata. 
fileData = fileobj['Body'].read()
print(fileData)


来源:https://stackoverflow.com/questions/49470585/accessing-a-specific-key-in-a-s3-bucket-using-boto3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!