How to access image by url on s3 using boto3?

What I want to accomplish is to generate a link to view the file (ex.image or pdf). The item is not accessible by URL (https://[bucket].s3.amazonaws.com/img_name.jpg), I think because its private and not public? (I'm not the owner of the bucket, but he gave me the access_key and secret_key?)

For now, all I can do is to download a file with this code.

s3.Bucket('mybucket').download_file('upload/nocturnes.png', 'dropzone/static/pdf/download_nocturnes.png') 

I want to access an image on s3 so I can put it on an HTML, can I view it using the access and secret key?. Thank you for those who can help!


You can accomplish this using a pre-signed URL using the generate_presigned_url function. The caveat is that pre-signed URLs must have an expiration date. I was unable to find documentation on the maximum allowed duration. Here is an example:

url = s3.generate_presigned_url('get_object',
                                Params={
                                    'Bucket': 'mybucket',
                                    'Key': 'upload/nocturnes.png',
                                },                                  
                                ExpiresIn=3600)
print url

For people who want to use generate_presigned_url for a public object and therefore don't want to do the signing part that appends credentials, the best solution I found is to still to use the generate_presigned_url , just that the Client.Config.signature_version needs to be set to botocore.UNSIGNED .

The following returns the public link without the signing stuff.

config.signature_version = botocore.UNSIGNED
boto3.client('s3', config=config).generate_presigned_url('get_object', ExpiresIn=0, Params={'Bucket': bucket, 'Key': key})

The relevant discussions on the boto3 repository are:

  • https://github.com/boto/boto3/issues/110
  • https://github.com/boto/boto3/issues/169
  • https://github.com/boto/boto3/issues/1415
  • 链接地址: http://www.djcxy.com/p/93548.html

    上一篇: 为什么我会在s3上显示图像时得到403 frobidden?

    下一篇: 如何使用boto3在s3上通过url访问图片?