Download remote_dir into (under) local_dir
(local_dir, remote_uri)
| 82 | SAT_BUCKET = 'sat' |
| 83 | |
| 84 | def download_s3(local_dir, remote_uri): |
| 85 | '''Download remote_dir into (under) local_dir |
| 86 | ''' |
| 87 | import boto3 |
| 88 | s3_resource = boto3.resource('s3', |
| 89 | endpoint_url = f'https://{SAT_ACCOUNT}.r2.cloudflarestorage.com', |
| 90 | aws_access_key_id = f'{SAT_ACCESS_KEY}', |
| 91 | aws_secret_access_key = f'{SAT_SECRET_KEY}' |
| 92 | ) |
| 93 | client = boto3.client('s3', |
| 94 | endpoint_url = f'https://{SAT_ACCOUNT}.r2.cloudflarestorage.com', |
| 95 | aws_access_key_id = f'{SAT_ACCESS_KEY}', |
| 96 | aws_secret_access_key = f'{SAT_SECRET_KEY}', |
| 97 | verify=False |
| 98 | ) |
| 99 | bucket = s3_resource.Bucket(SAT_BUCKET) |
| 100 | transfer_config = boto3.s3.transfer.TransferConfig( |
| 101 | use_threads=True, |
| 102 | multipart_threshold=8*1024*1024, |
| 103 | max_concurrency=64, |
| 104 | multipart_chunksize=8*1024*1024, |
| 105 | ) |
| 106 | # remote_uri is file |
| 107 | if '.' in os.path.basename(remote_uri): |
| 108 | bucket.download_file(remote_uri, os.path.join(local_dir, os.path.basename(remote_uri)),Callback=ProgressPercentage(client, SAT_BUCKET, remote_uri), Config=transfer_config) |
| 109 | return |
| 110 | # uri is path |
| 111 | remote_dir = remote_uri |
| 112 | key_prefix = remote_dir.split('/')[:-1] |
| 113 | for obj in bucket.objects.filter(Prefix = remote_dir): |
| 114 | key_suffix = obj.key[len(key_prefix):] # remote_dir/xxx/xxx.zip |
| 115 | target_dir = os.path.join(local_dir, os.path.dirname(key_suffix)) |
| 116 | if not os.path.exists(target_dir): |
| 117 | os.makedirs(target_dir) |
| 118 | # skip if exists |
| 119 | if os.path.exists(os.path.join(local_dir, key_suffix)) and os.path.getsize(os.path.join(local_dir, key_suffix)) == obj.size: |
| 120 | continue |
| 121 | bucket.download_file(obj.key, os.path.join(local_dir, key_suffix),Callback=ProgressPercentage(client, SAT_BUCKET, obj.key), Config=transfer_config) |
| 122 | |
| 123 | |
| 124 | class ProgressPercentage(object): |
no test coverage detected