我有此代码为匹配字符串的最近对象生成预签名URL。
问题是,在生成URL时如何将正确的区域传递给s3客户端,如果未生成正确的url,则此代码无用。
#! /usr/bin/python
#This script generates S3 object pre-signed URL
import logging
import boto3
from botocore.exceptions import ClientError
def keys(bucket_name, prefix="", delimiter="/"):
"""Generate a key listings
:param bucket_name: string
:param prefix: string
:param delimiter: string
"""
for page in (
boto3.client("s3")
.get_paginator("list_objects_v2")
.paginate(
Bucket=bucket_name,
Prefix=prefix[len(delimiter) :] if prefix.startswith(delimiter) else prefix,
**{"StartAfter": prefix} if prefix.endswith(delimiter) else {}
)
):
for content in page.get("Contents", ()):
yield content["Key"]
def latest(bucket_name, prefix):
"""Generate a latest logfile
:param bucket_name: string
:param prefix: string
:return: Object keys
"""
return(max(i for i in keys(bucket_name) if prefix in i))
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:
logging.error(e)
return None
# The response contains the presigned URL
return response
print(create_presigned_url("database-backup", latest("database-backup", "my-backup")))```
优化@john的答案。
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.session.Session(
region_name=boto3.client('s3').get_bucket_location(Bucket=bucket_name)["LocationConstraint"]
).client("s3")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句