How to access image by url on s3 using boto3?

久未见 提交于 2019-12-22 18:37:36

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/43973658/how-to-access-image-by-url-on-s3-using-boto3

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