Python - Django 計算 阿里雲 oss 所有檔案的總大小
阿新 • • 發佈:2020-12-15
import oss2 auth = oss2.Auth(settings.OSS_ACCESS_KEY_ID, settings.OSS_ACCESS_KEY_SECRET) bucket = oss2.Bucket(auth, settings.OSS_ENDPOINT, settings.OSS_BUCKET_NAME) def CalculateFolderLength(bucket, folder): length = 0 for obj in oss2.ObjectIterator(bucket, prefix=folder, max_keys=1000): length+= obj.size return length # ObjectIterator 會列舉所有的檔案或目錄,但每次迴圈列舉100個,可以通過 max_keys 來調整數目,最大值為 1000 def get_size(): size = 0 for obj in oss2.ObjectIterator(bucket, delimiter='/'): if obj.is_prefix(): # 資料夾 length = CalculateFolderLength(bucket, obj.key) size += lengthelse: size += obj.size return size def StrOfSize(size): ''' 遞迴實現,精確為最大單位值 + 小數點後三位 ''' def strofsize(integer, remainder, level): if integer >= 1024: remainder = integer % 1024 integer //= 1024 level += 1 return strofsize(integer, remainder, level)else: return integer, remainder, level units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] integer, remainder, level = strofsize(size, 0, 0) if level+1 > len(units): level = -1 return ( '{}.{:>03d} {}'.format(integer, remainder, units[level]) ) print(StrOfSize(get_size()))