如何使用 Amazon S3 Uri 链接下载图片?

how to use Amazon S3 Uri links to download image?

场景是,我有 s3:// 类型的链接可以使用,我应该编写一个脚本来从该链接下载图像,我不太清楚该怎么做,尝试阅读一些帖子、文档没有太大帮助,最终脚本抛出了一些我不明白的异常,我在这里使用了 boto3。

所以基本上我得到了这些链接 s3://some-name-with-hyphens/other/and_one_more/some.jpg 我需要编写 python 脚本来下载该对象。

这些图像托管在 public AWS S3 存储桶上。

这是我使用的脚本,我在这里显示假的 s3 uri:

import boto3
def find_bucket_key(s3_path):
    """
    This is a helper function that given an s3 path such that the path is of
    the form: bucket/key
    It will return the bucket and the key represented by the s3 path
    """
    s3_components = s3_path.split('/')
    bucket = s3_components[0]
    s3_key = ""
    if len(s3_components) > 1:
        s3_key = '/'.join(s3_components[1:])
    return bucket, s3_key


def split_s3_bucket_key(s3_path):
    """Split s3 path into bucket and key prefix.
    This will also handle the s3:// prefix.
    :return: Tuple of ('bucketname', 'keyname')
    """
    if s3_path.startswith('s3://'):
        s3_path = s3_path[5:]
    return find_bucket_key(s3_path)


client = boto3.client('s3')
bucket_name, key_name = split_s3_bucket_key(
    's3://some-name-with-hyphens/other/and_one_more/some.jpg')
response = client.get_object(Bucket=bucket_name, Key=key_name)

我得到的异常是:

File "C:\Users\BASAVARAJ\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\botocore\auth.py", line 373, in add_auth
raise NoCredentialsError()
botocore.exceptions.NoCredentialsError: Unable to locate credentials

如果您没有执行请求的 AWS 凭证,则需要执行未签名的请求。用此替换客户端创建以创建不会签署任何请求的客户端:

import boto3
from botocore import UNSIGNED
from botocore.config import Config
client = boto3.client('s3', config=Config(signature_version=UNSIGNED))