当使用AWS CloudFront预签名URL时,如果S3存储桶没有启用Origin Access Identity(OAI),可能会遇到问题。以下是解决该问题的代码示例:
首先,确保您已经安装了AWS SDK for Python(boto3)。
使用以下代码创建一个预签名URL:
import boto3
from botocore.exceptions import ClientError
def create_presigned_url(bucket_name, object_name, expiration=3600):
"""Generate a presigned URL to share an S3 object
:param bucket_name: string
:param object_name: string
:param expiration: Time in seconds for the presigned URL to remain valid
:return: Presigned URL as string. If error, returns None.
"""
# Generate a presigned URL for the S3 object
s3_client = boto3.client('s3')
try:
response = s3_client.generate_presigned_url('get_object',
Params={'Bucket': bucket_name,
'Key': object_name},
ExpiresIn=expiration)
except ClientError as e:
print(e)
return None
# The response contains the presigned URL
return response
# 指定S3存储桶名称和对象键
bucket_name = 'your-bucket-name'
object_name = 'your-object-key'
# 创建预签名URL
presigned_url = create_presigned_url(bucket_name, object_name)
# 打印预签名URL
print(presigned_url)
确保将your-bucket-name
和your-object-key
替换为实际的存储桶名称和对象键。
通过使用以上代码,您将能够获取到CloudFront预签名URL,即使S3存储桶没有启用OAI。