简体   繁体   English

使用Amazon s3 boto库,如何获取已保存密钥的URL?

[英]Using Amazon s3 boto library, how can I get the URL of a saved key?

I am saving a key to a bucket with: 我正在保存一个桶的密钥:

    key = bucket.new_key(fileName)
    key.set_contents_from_string(base64.b64decode(data))
    key.set_metadata('Content-Type', 'image/jpeg')
    key.set_acl('public-read')

After the save is successful, how can I access the URL of the newly created file? 保存成功后,如何访问新创建的文件的URL?

If the key is publicly readable (as shown above) you can use Key.generate_url : 如果密钥是公开可读的(如上所示),您可以使用Key.generate_url

url = key.generate_url(expires_in=0, query_auth=False)

If the key is private and you want to generate an expiring URL to share the content with someone who does not have direct access you could do: 如果密钥是私有的,并且您希望生成一个过期的URL以与没有直接访问权限的人共享内容,您可以执行以下操作:

url = key.generate_url(expires_in=300)

where expires is the number of seconds before the URL expires. expires是URL到期前的秒数。 These will produce HTTPS url's. 这些将生成HTTPS网址。 If you prefer an HTTP url, use this: 如果您更喜欢HTTP网址,请使用以下命令:

url = key.generate_url(expires_in=0, query_auth=False, force_http=True)

For Boto3, you need to do it the following way... 对于Boto3,您需要按以下方式执行此操作...

import boto3

s3 = boto3.client('s3')
url = '{}/{}/{}'.format(s3.meta.endpoint_url, bucket, key)
import boto
from boto.s3.connection import S3Connection

conn = S3Connection('AWS_ACCESS_KEY', 'AWS_SECRET_KEY')

secure_https_url = 'https://{host}/{bucket}/{key}'.format(
    host=conn.server_name(),
    bucket='name-of-bucket',
    key='name_of_key')

http_url = 'http://{bucket}.{host}/{key}'.format(
    host=conn.server_name(),
    bucket='name-of-bucket',
    key='name_of_key')

That's how I did it in boto 2.23.0 for a public URL. 这就是我在boto 2.23.0中为公共URL做的。 I couldn't get the expires_in=None argument to work. 我无法使用expires_in = None参数。

Note that for HTTPS you can't use a subdomain. 请注意,对于HTTPS,您无法使用子域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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