gpt4 book ai didi

python - 如何获取存储桶区域并将其传递给客户端 o 生成预签名 URLS aws s3

转载 作者:行者123 更新时间:2023-12-05 08:38:50 25 4
gpt4 key购买 nike

我有这段代码可以为最近匹配字符串的对象生成预签名 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")))```

最佳答案

扩展@wpp 的回答,您的代码将如下所示:

def create_presigned_url(bucket_name, object_name, expiration=3600):

# Get region for bucket
s3_client = boto3.client('s3')
response = s3_client.get_bucket_location(Bucket=bucket_name)

# Generate a presigned URL for the S3 object
s3_client = boto3.client('s3', region_name=response['LocationConstraint'])
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

关于python - 如何获取存储桶区域并将其传递给客户端 o 生成预签名 URLS aws s3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61428338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com