我正在嘗試從我的 s3 存盤桶下載檔案夾。我想使用 s3.client 因為我在代碼中進一步使用了客戶端方法,但我無法使用客戶端方法訪問存盤桶。當我使用“s3Client.Bucket(bucketName)”時,我收到一條錯誤訊息,指出它沒有屬性 Bucket。當我使用“s3Client.get_object(Bucket=bucketName, Key=?)”首先它說需要密鑰,應該是什么密鑰,是我要下載的檔案夾嗎?請讓我知道我在這里做錯了什么。謝謝你。
awsParams = {
"bucket_name": "asgard-icr-model",
"region_name": "ap-south-1"
}
def get_s3_client():
s3Client = boto3.client('s3')
return s3Client
def download_from_s3(srcDir, dstDir):
try:
bucketName = awsParams['bucket_name'] #s3 bucket name
s3Client = get_s3_client()
bucket = s3Client.Bucket(bucketName) # I get error saying - client has no attribute Bucket.
bucket = s3Client.get_object(Bucket=bucketName, Key= ?) # If I use this line instead of previous, what should be my key here?
所以現在如果我做這個改變,我應該用什么代替list_objects_v2()ins3.resource因為沒有這個名字的屬性?
def get_s3_object():
s3Obj = boto3.resource("s3",region_name=awsParams['region_name'])
return s3Obj
def download_from_s3(srcDir, dstDir):
try:
bucketName = awsParams['bucket_name'] #s3 bucket name
# s3Client = get_s3_client()
# bucket = s3Client.Bucket(bucketName)
# bucket = s3Client.get_object(Bucket=bucketName, Key=)
s3Obj = get_s3_object()
bucket = s3Obj.Bucket(bucketName)
keys = []
dirs = []
next_token = ''
base_kwargs = {
'Bucket':bucket,
'srcDir':srcDir,
}
while next_token is not None:
kwargs = base_kwargs.copy()
if next_token != '':
kwargs.update({'ContinuationToken': next_token})
**results = s3Client.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))
for k in keys:
dest_pathname = os.path.join(local, k)
if not os.path.exists(os.path.dirname(dest_pathname)):
os.makedirs(os.path.dirname(dest_pathname))
s3Client.download_file(bucket, k, dest_pathname)
except Exception as e:
raise
uj5u.com熱心網友回復:
使用 aclient時,您可以獲得物件串列:
s3_client = boto3.client('s3')
results = s3_client.list_objects_v2(Bucket=...)
for object in results['Contents']:
print(object['Key'])
使用時resource,您可以使用:
s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket('Bucketname')
for object in bucket.objects.all():
print(object.key)
uj5u.com熱心網友回復:
您應該使用a resource,而不是client:
s3Resource = boto3.resource('s3')
return s3Resource
然后結束
bucket = s3Resource.Bucket(bucketName)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450565.html
