本文介绍了如何使用Amazon S3 URI链接下载图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
场景是,我有s3://
类型的链接要处理,我应该编写一个脚本来从这些链接下载图像,我不太知道该怎么做,尝试阅读一些帖子,文档没有太大帮助,最后得到的脚本抛出了一些我不理解的异常,我在这里使用了boto3。
所以基本上我得到了这些链接s3://some-name-with-hyphens/other/and_one_more/some.jpg
我需要编写python脚本来下载该对象。
这些映像托管在公共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:UsersBASAVARAJAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagesotocoreauth.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))
这篇关于如何使用Amazon S3 URI链接下载图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!