简体   繁体   中英

Download files from public S3 bucket with boto3

I cannot download a file or even get a listing of the public S3 bucket with boto3 .

The code below works with my own bucket, but not with public one:

def s3_list(bucket, s3path_or_prefix):
    bsession = boto3.Session(aws_access_key_id=settings.AWS['ACCESS_KEY'],
                             aws_secret_access_key=settings.AWS['SECRET_ACCESS_KEY'],
                             region_name=settings.AWS['REGION_NAME'])
    s3 = bsession.resource('s3')
    my_bucket = s3.Bucket(bucket)
    items = my_bucket.objects.filter(Prefix=s3path_or_prefix)
    return [ii.key for ii in items]

I get an AccessDenied error on this code. The bucket is not in my own and I cannot set permissions there, but I am sure it is open to public read.

I had the similar issue in the past. I have found a key to this bug in https://github.com/boto/boto3/issues/134 .

You can use undocumented trick:

import botocore


def s3_list(bucket, s3path_or_prefix, public=False):
    bsession = boto3.Session(aws_access_key_id=settings.AWS['ACCESS_KEY'],
                             aws_secret_access_key=settings.AWS['SECRET_ACCESS_KEY'],
                             region_name=settings.AWS['REGION_NAME'])
    client = bsession.client('s3')
    if public:
        client.meta.events.register('choose-signer.s3.*', botocore.handlers.disable_signing)
    result = client.list_objects(Bucket=bucket, Delimiter='/', Prefix=s3path_or_prefix)
    return [obj['Prefix'] for obj in result.get('CommonPrefixes')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM