如何在Python中使用boto3检查S3上传的状态

时间:2018-10-30 04:53:07

标签: python boto3

这是我的代码,使用python在bo3中上传文件到S3存储桶。

import boto3

def upload_to_s3(backupFile, s3Bucket, bucket_directory, file_format):
    s3 = boto3.resource('s3')
    s3.meta.client.upload_file(backupFile, s3Bucket, bucket_directory.format(file_format))

upload_to_s3('/tmp/backup.py', 'bsfbackup', 'pfsense/{}', 'hello.py')

我的问题是,上载成功后,我要打印“上载成功”,如果上载失败,则要打印“上载失败”和错误堆栈。 有帮助吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

try:
   response = s3_client.upload_file(file_name, bucket, object_name)
except ClientError as e:
   logging.error(e)
   return False
return True

答案 1 :(得分:0)

上传,你也可以使用这个替代方法,

回调会告诉你已经传输了多少字节的数据

from boto3.s3.transfer import S3Transfer
import threading 

def upload(file, input):
    transfer = S3Transfer(s3)
    size = float(os.path.getsize(file))
    transfer.upload_file(**input,
                         callback=_progress(file, size, 'Upload'))

def _progress(filename, size, ops):
    """ indicator to calculate progress based on filesize
    """
    _filename = filename
    _size = size
    _seen_so_far = 0
    _ops = ops
    _lock = threading.Lock()

    def call(bytes_amount):
        with _lock:
            nonlocal _seen_so_far
            _seen_so_far += bytes_amount
            percentage = (_seen_so_far / _size) * 100
            logging.info(
                "%s: %s  %s / %s  (%.2f%%)" % (
                    _ops, _filename, _seen_so_far, _size,
                    percentage))

    return call