【问题标题】:Using boto Upload file to S3 sub folder when I have no permissions on listing folders of S3 bucket当我没有权限列出 S3 存储桶的文件夹时,使用 boto 将文件上传到 S3 子文件夹
【发布时间】:2015-09-01 12:18:49
【问题描述】:

我的存储桶“basebucket”中有一个子文件夹“my/places/photos”。我对此子文件夹具有读写和删除权限。但是我对 basebucket 没有权限。

是否有使用 Python boto 可以将文件分段上传到“my/places/photos”的方法。

我编写了以下代码但无法正常工作。存储桶对象本身没有被创建。给我一个例外。如果我尝试查找,我将桶对象设为无。

def file_multipart_upload():
    conn = S3Connection(ACCESS_KEY, SECRET_KEY)
    bucket = conn.get_bucket(BUCKET_NAME)

    # Get file info
    file_to_upload = FILE_TO_UPLOAD
    source_size = os.stat(file_to_upload).st_size
    chunk_size = 5242880

    # Create a multipart upload request
    mp = bucket.initiate_multipart_upload(os.path.join(BUCKET_FOLDER_PATH, file_to_upload))
    chunk_count = int(math.ceil(source_size / float(chunk_size)))
    print("Chunk size is {0} for the file {1}".format(chunk_count, file_to_upload))

    # Send the file parts, using FileChunkIO to create a file-like object
    # that points to a certain byte range within the original file. We
    # set bytes to never exceed the original file size.
    for i in range(chunk_count):
        offset = chunk_size * i
        bytes = min(chunk_size, source_size - offset)
        with FileChunkIO(file_to_upload, 'r', offset=offset, bytes=bytes) as fp:
            mp.upload_part_from_file(fp, part_num=i + 1)
        print("Offset, bytes and part_num values of file {0} are {1}, {2} and {3}".format(file_to_upload, offset,
                                                                                          bytes, i + 1))
    # Finish the upload
    mp.complete_upload()

【问题讨论】:

  • 顺便说一下,我使用的是 boto 2.38 而不是 boto3。

标签: python amazon-s3 boto


【解决方案1】:

默认情况下,boto get_bucket 方法调用会尝试通过对存储桶 url 执行 HEAD 请求来验证存储桶是否存在。这将要求您具有列出存储桶的权限。

如果您想避免此验证步骤,只需执行以下操作:

bucket = conn.get_bucket(BUCKET_NAME, validate=False)

boto 将跳过验证步骤。

【讨论】:

    猜你喜欢
    • 2018-04-19
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    相关资源
    最近更新 更多