Hyp*_*vil 4 python amazon-s3 amazon-web-services boto3 python-3.6
上传文件后,我需要直接检索公共对象URL,以便能够将其存储在数据库中。这是我的上传代码:
s3 = boto3.resource('s3')
s3bucket.upload_file(filepath, objectname, ExtraArgs={'StorageClass': 'STANDARD_IA'})
Run Code Online (Sandbox Code Playgroud)
我不是在寻找预先签名的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)
Run Code Online (Sandbox Code Playgroud)
从2010年开始,您可以使用虚拟主机样式的S3网址,即,无需弄乱区域特定的网址:
url = 'https://%s.s3.amazonaws.com/%s' % (bucket, key)
Run Code Online (Sandbox Code Playgroud)
此外,在2020年9月30日或之前创建的存储桶将继续支持路径样式模型(特定于区域的url)。在该日期之后创建的存储桶必须使用虚拟托管模型进行引用。
另请参阅此博客文章。
对于键中的某些特殊字符(例如:“+”),连接原始键将失败,您必须引用它们:
url = "https://s3-%s.amazonaws.com/%s/%s" % (
location,
bucket_name,
urllib.parse.quote(key, safe="~()*!.'"),
)
Run Code Online (Sandbox Code Playgroud)
或者您可以致电:
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}
)
Run Code Online (Sandbox Code Playgroud)
...如此处所述。
| 归档时间: |
|
| 查看次数: |
4019 次 |
| 最近记录: |