import oss2 # 连接 oss 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): # 列举所有的文件或目录,但每次循环列举100个,可以通过 max_keys 来调整数目,最大值为 1000 length = 0 for obj in oss2.ObjectIterator(bucket, prefix=folder, max_keys=1000): length += obj.size return length def get_size(): # 计算所有文件总大小 size = 0 for obj in oss2.ObjectIterator(bucket, delimiter='/'): if obj.is_prefix(): # 文件夹 length = CalculateFolderLength(bucket, obj.key) size += length else: 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()))
参考文章(大小单位转换): https://blog.csdn.net/wskzgz/article/details/99293181