対象読者
boto3が提供しているAPIが get_presigned_url
しかなくて困った仔羊に向けて
S3オブジェクトのpublicなURLを取得する場合のコード
aws.py
import boto3
s3 = boto3.client('s3')
def get_public_url(bucket, target_object_path):
"""
対象のS3ファイルのURLを取得する
Parameters
----------
bucket: string
S3のバケット名
target_object_path: string
取得したいS3内のファイルパス
Returns
----------
url: string
S3上のオブジェクトのURL
"""
bucket_location = s3.get_bucket_location(Bucket=bucket)
return "https://s3-{0}.amazonaws.com/{1}/{2}".format(
bucket_location['LocationConstraint'],
bucket,
target_object_path)
LocationConstraintの取得でAccess Deniedが出る場合
S3バケットのバケットポリシーを以下に設定する
bucket_policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AddPerm",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:GetObject",
"s3:GetBucketLocation"
],
"Resource": [
"arn:aws:s3:::[バケット名]/*",
"arn:aws:s3:::[バケット名]"
]
}
]
}
参考文献