如何使用 Python 中的 Boto3 库使用 AWS 资源上传 S3 中的对象?
问题陈述-使用Python中的Boto3库将对象上传到S3。比如如何上传test.zip到S3的Bucket_1。
解决这个问题的方法/算法
步骤1-导入boto3和botocore异常以处理异常。
步骤2-从pathlib,导入PurePosixPath以从路径检索文件名
步骤3-s3_path和filepath是函数upload_object_into_s3中的两个参数
步骤4-验证s3_path在AWS格式通过如S3://BUCKET_NAME/键和文件路径为本地路径C://用户/文件名
步骤5-使用boto3库创建AWS会话。
步骤6-为S3创建AWS资源。
Step7-拆分S3路径并执行操作以分离根存储桶名称和密钥路径
步骤8-获取完整文件路径的文件名并添加到S3密钥路径中。
第9步-现在使用函数upload_fileobj将本地文件上传到S3。
步骤10-使用函数wait_until_exists等待操作完成。
步骤11-根据响应代码处理异常以验证文件是否已上传。
第12步-如果上传文件时出现问题,处理通用异常
示例
使用以下代码将文件上传到AWSS3-
import boto3
frombotocore.exceptionsimport ClientError
from pathlib import PurePosixPath
def upload_object_into_s3(s3_path, filepath):
if 's3://' in filepath:
print('SourcePath is not a valid path.' + filepath)
raise Exception('SourcePath is not a valid path.')
elif s3_path.find('s3://') == -1:
print('DestinationPath is not a s3 path.' + s3_path)
raise Exception('DestinationPath is not a valid path.')
session = boto3.session.Session()
s3_resource = session.resource('s3')
tokens = s3_path.split('/')
target_key = ""
if len(tokens) > 3:
for tokn in range(3, len(tokens)):
if tokn == 3:
target_key += tokens[tokn]
else:
target_key += "/" + tokens[tokn]
target_bucket_name = tokens[2]
file_name = PurePosixPath(filepath).name
if target_key != '':
target_key.strip()
key_path = target_key + "/" + file_name
else:
key_path = file_name
print(("key_path: " + key_path, 'target_bucket: ' + target_bucket_name))
try:
#从本地路径上传实体
with open(filepath, "rb") as file:
s3_resource.meta.client.upload_fileobj(file, target_bucket_name, key_path)
try:
s3_resource.Object(target_bucket_name, key_path).wait_until_exists()
file.close()
except ClientError as error:
error_code = int(error.response['Error']['Code'])
if error_code == 412 or error_code == 304:
print("Object didn't Upload Successfully ", target_bucket_name)
raise error
return "Object Uploaded Successfully"
except Exception as error:
print("s3helper上传对象函数出错: " + error.__str__())
raise error
print(upload_object_into_s3('s3://Bucket_1/testfolder', 'c://test.zip'))输出结果key_path:/testfolder/test.zip, target_bucket: Bucket_1 Object Uploaded Successfully