[英]Generate presigned s3 URL of latest object in the bucket using boto3
I have a s3 bucket with multiple folders.我有一个带有多个文件夹的 s3 存储桶。 How can I generate s3 presigned URL for a latest object using python boto3 in aws for each folder asked by a user?
如何在aws中为用户询问的每个文件夹使用python boto3为最新的object生成s3 presigned URL?
If it's a small bucket then recursively list the bucket, with prefix as needed.如果它是一个小桶,则递归列出该桶,并根据需要使用前缀。 Sort the results by timestamp, and create the pre-signed URL for the latest.
按时间戳对结果进行排序,并为最新创建预签名的 URL。
If it's a very large bucket, this will be very inefficient and you should consider other ways to store the key of the latest file.如果是一个非常大的桶,这将是非常低效的,您应该考虑其他方式来存储最新文件的密钥。 For example: trigger a Lambda function whenever an object is uploaded and write that object's key into a LATEST item in DynamoDB (or other persistent store).
例如:每当上传 object 时触发 Lambda function 并将该对象的密钥写入 DynamoDB(或其他持久存储)中的最新项目。
You can do something like你可以做类似的事情
import boto3
from botocore.client import Config
import requests
bucket = 'bucket-name'
folder = '/' #you can add folder path here don't forget '/' at last
s3 = boto3.client('s3',config=Config(signature_version='s3v4'))
objs = s3.list_objects(Bucket=bucket, Prefix=folder)['Contents']
latest = max(objs, key=lambda x: x['LastModified'])
print(latest)
print (" Generating pre-signed url...")
url = s3.generate_presigned_url(
ClientMethod='get_object',
Params={
'Bucket': bucket,
'Key': latest['Key']
}
)
print(url)
response = requests.get(url)
print(response.url)
here it will give the latest last modified file from the whole bucket however you can update login and update prefix value as per need.在这里它将提供整个存储桶中最新的最后修改文件,但是您可以根据需要更新登录名和更新前缀值。
if you are using Kubernetes POD, VM, or anything you can pass environment variables or use the python dict to store the latest key if required.如果您使用 Kubernetes POD、VM 或任何您可以传递环境变量或使用 python 字典来存储最新密钥(如果需要)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.