如何在Python中从S3分段下载大文件?

use*_*197 6 python multipart download amazon-s3

我正在寻找一些 Python 代码,允许我从 S3 进行大文件的分段下载。我找到了这个github 页面,但是它太复杂了,所有命令行参数传递和解析器以及其他东西让我很难理解代码。我并不是在寻找任何花哨的东西,而是想要一个基本的代码,这样我就可以静态地将 2-3 个文件名放入其中,并让它执行这些文件的分段下载。

谁能给我提供这样的解决方案或链接?或者也许可以帮助我清理上面发布的链接中的代码?

wes*_*ywh 1

这是旧的,但这是我为使其发挥作用所做的事情:

conn.download_file(
    Bucket=bucket,
    Filename=key.split("/")[-1],
    Key=key,
    Config=boto3.s3.transfer.TransferConfig(
        max_concurrency=parallel_threads
    )
)
Run Code Online (Sandbox Code Playgroud)

以下是我在一些漂亮的可视化代码中使用它的方法:

import boto3
import math
import os
import time


def s3_get_meta_data(conn, bucket, key):
    meta_data = conn.head_object(
    Bucket=bucket,
    Key=key
)
return meta_data


def s3_download(conn, bucket, key, parallel_threads):
    start = time.time()
    md = s3_get_meta_data(conn, bucket, key)
    chunk = get_cunks(md["ContentLength"], parallel_threads)
    print("Making %s parallel s3 calls with a chunk size of %s each..." % (
        parallel_threads, convert_size(chunk))
    )
    cur_dir = os.path.dirname(os.path.realpath(__file__))
    conn.download_file(
        Bucket=bucket,
        Filename=key.split("/")[-1],
        Key=key,
        Config=boto3.s3.transfer.TransferConfig(
            max_concurrency=parallel_threads
        )
    )
    end = time.time() - start
    print("Finished downloading %s in %s seconds" % (key, end))


def convert_size(size_bytes):
    if size_bytes == 0:
        return "0B"
    size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
    i = int(math.floor(math.log(size_bytes, 1024)))
    p = math.pow(1024, i)
    s = round(size_bytes / p, 2)
    return "%s %s" % (s, size_name[i])


def get_cunks(size_bytes, desired_sections):
    return size_bytes / desired_sections


session = boto3.Session(profile_name="my_profile")
conn = session.client("s3", region_name="us-west-2")

s3_download(
    conn,
    "my-bucket-name",
    "my/key/path.zip",
    5
)
Run Code Online (Sandbox Code Playgroud)

可以向 Config 参数提供更多信息,请在 aws 文档中阅读:

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/s3.html#boto3.s3.transfer.TransferConfig