如何使用Boto3库在Python中使用AWS资源上传S3中的对象?

如何使用Boto3库在Python中使用AWS资源上传S3中的对象?

问题陈述 - 使用Python中的Boto3库上传对象到S3。例如,如何将test.zip上传到S3的Bucket_1中。

更多Python相关文章,请阅读:Python 教程

解决此问题的方法/算法

第一步 - 导入boto3和botocore异常以处理异常。

第二步 - 从 pathlib 中导入PurePosixPath以从路径中检索文件名

第三步 - s3_pathfilepath 是函数 upload_object_into_s3 的两个参数

第四步 - 验证 s3_path 是否以AWS格式 s3://bucket_name/key 传递,而 filepath 作为本地路径C://用户/文件名

第五步 - 使用boto3库创建AWS会话。

第六步 - 为S3创建AWS资源。

第七步 - 拆分S3路径并执行操作以分离根桶名称和键路径

第八步 - 获取完整文件路径的文件名,并将其添加到S3键路径中。

第九步 - 现在使用函数 upload_fileobj 将本地文件上传到S3。

第十步 - 使用函数 wait_until_exists 等待操作完成。

第十一步 - 基于响应代码处理异常,以验证是否已上传文件。

第十二步 - 如果上传文件时发生了错误,请处理通用异常

示例

使用以下代码将文件上传到AWS S3 –

import boto3
from botocore.exceptions import 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:
      # uploading Entity from local path
      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("Error in upload object function of s3 helper: " + 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程