![](/img/trans.png)
[英]How to get a downloadable url of S3 bucket itself not an object url using python, boto3?
[英]Python 3 Boto 3, AWS S3: Get object URL
我需要在上傳文件后直接檢索公共對象 URL,以便能夠將其存儲在數據庫中。 這是我的上傳代碼:
s3 = boto3.resource('s3')
s3bucket.upload_file(filepath, objectname, ExtraArgs={'StorageClass': 'STANDARD_IA'})
我不是在尋找預先簽名的 URL,而是始終可以通過 https 公開訪問的 URL。
任何幫助表示贊賞。
沒有簡單的方法,但您可以從存儲桶所在的區域 ( get_bucket_location
)、存儲桶名稱和存儲密鑰構建 URL:
bucket_name = "my-aws-bucket"
key = "upload-file"
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket_name)
bucket.upload_file("upload.txt", key)
location = boto3.client('s3').get_bucket_location(Bucket=bucket_name)['LocationConstraint']
url = "https://s3-%s.amazonaws.com/%s/%s" % (location, bucket_name, key)
自 2010 年以來,您可以使用虛擬托管樣式的 S3 網址,即無需弄亂特定於區域的網址:
url = f'https://{bucket}.s3.amazonaws.com/{key}'
帶引號的鍵:
url = f'''https://{bucket}.s3.amazonaws.com/{urllib.parse.quote(key, safe="~()*!.'")}'''
此外,對於 2020 年 9 月 30 日或之前創建的存儲桶,將繼續支持路徑樣式模型(特定於區域的 url)。必須使用虛擬托管模型引用該日期之后創建的存儲桶。
另請參閱此博客文章。
對於鍵中的某些特殊字符(例如:'+'),連接原始鍵將失敗,您必須引用它們:
url = "https://s3-%s.amazonaws.com/%s/%s" % (
location,
bucket_name,
urllib.parse.quote(key, safe="~()*!.'"),
)
或者您可以致電:
my_config = Config(signature_version = botocore.UNSIGNED)
url = boto3.client("s3", config=my_config).generate_presigned_url(
"get_object", ExpiresIn=0, Params={"Bucket": bucket_name, "Key": key}
)
...描述這里。
您可以生成預先簽名的 URL,然后修剪其查詢參數。 這需要相關存儲桶的“s3:PutObject”權限。
url = s3client.generate_presigned_url(ClientMethod = 'put_object',
Params = { 'Bucket': bucket_name, 'Key': key })
# trim query params
url = url[0 : url.index('?')]
只是一個小筆記。 函數調用
location =
boto3.client('s3').get_bucket_location(Bucket=bucket_name['LocationConstraint']
如果存儲桶位於“us-east-1”區域,則可能返回 location = None。 因此,我會修改上面的答案並在該行下方添加一行:
if location == None: location = 'us-east-1'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.