Python 使用 Amazon s3 boto 库,如何获取已保存密钥的 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16156062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Amazon s3 boto library, how can I get the URL of a saved key?
提问by S-K'
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?
采纳答案by garnaat
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 expiresis the number of seconds before the URL expires. These will produce HTTPS url's. If you prefer an HTTP url, use this:
其中expires是 URL 过期前的秒数。这些将产生 HTTPS 网址。如果您更喜欢 HTTP url,请使用以下命令:
url = key.generate_url(expires_in=0, query_auth=False, force_http=True)
回答by kumar303
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. I couldn't get the expires_in=None argument to work.
这就是我在 boto 2.23.0 中为公共 URL 所做的。我无法让 expires_in=None 参数起作用。
Note that for HTTPS you can't use a subdomain.
请注意,对于 HTTPS,您不能使用子域。
回答by treecoder
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)

