【问题标题】:awscli sync method for boto3boto3 的 awscli 同步方法
【发布时间】:2021-10-15 00:56:39
【问题描述】:

要从 S3 复制我们在 awscli 命令下面使用的所有文件

aws s3 sync s3://my-bucket / . --exclude "test-files/*" --region us-east-1

现在我想使用 boto3 模块复制 lambda python 代码中的所有文件。

我在 boto 中找不到任何可以完成同步工作的方法。

【问题讨论】:

    标签: amazon-web-services amazon-s3 aws-lambda boto3 aws-cli


    【解决方案1】:

    Boto3 中没有sync 命令。如果您仍想这样做,可以在代码中启动 subprocess 并运行 aws s3 sync s3://my-bucket / . --exclude "test-files/*" --region us-east-1

    我不确定 aws-cli 是否已预安装在 Lambda 执行环境中,因此您可能需要先检查一下。您始终可以将其安装为依赖项。

    【讨论】:

    • 你能给我一些参考如何在 lambda 中安装 aws-cli
    • pip install awscli
    • 从 AWS Lambda 函数调用 AWS CLI 有点小技巧。更好的方法是编写自己的代码来执行等效操作。但是,如果它有效......那就去吧!
    【解决方案2】:

    尝试使用此代码...

    from concurrent import futures
    import os
    import boto3
    
    def download_dir(prefix, local, bucket):
    
        client = boto3.client('s3')
    
        def create_folder_and_download_file(k):
            dest_pathname = os.path.join(local, k)
            if not os.path.exists(os.path.dirname(dest_pathname)):
                os.makedirs(os.path.dirname(dest_pathname))
            print(f'downloading {k} to {dest_pathname}')
            client.download_file(bucket, k, dest_pathname)
    
        keys = []
        dirs = []
        next_token = ''
        base_kwargs = {
            'Bucket': bucket,
            'Prefix': prefix,
        }
        while next_token is not None:
            kwargs = base_kwargs.copy()
            if next_token != '':
                kwargs.update({'ContinuationToken': next_token})
            results = client.list_objects_v2(**kwargs)
            contents = results.get('Contents')
            for i in contents:
                k = i.get('Key')
                if k[-1] != '/':
                    keys.append(k)
                else:
                    dirs.append(k)
            next_token = results.get('NextContinuationToken')
        for d in dirs:
            dest_pathname = os.path.join(local, d)
            if not os.path.exists(os.path.dirname(dest_pathname)):
                os.makedirs(os.path.dirname(dest_pathname))
        with futures.ThreadPoolExecutor() as executor:
            futures.wait(
                [executor.submit(create_folder_and_download_file, k) for k in keys],
                return_when=futures.FIRST_EXCEPTION,
            )
    download_dir('' , 'foldername/path', 'bucket-name')
    
    

    根据需要更改前缀或将其留空以复制存储桶中的所有文件。

    【讨论】:

      猜你喜欢
      • 2022-10-16
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      相关资源
      最近更新 更多