Expand get_size() function

This commit is contained in:
CorpNewt 2019-09-07 15:16:41 -05:00 committed by GitHub
parent 474f009c1c
commit 23b4c8c932
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 31 additions and 15 deletions

View File

@ -38,26 +38,42 @@ class Downloader:
return None
return response
def get_size(self, size, suff=None):
def get_size(self, size, suffix=None, use_1024=False, round_to=2, strip_zeroes=False):
# size is the number of bytes
# suffix is the target suffix to locate (B, KB, MB, etc) - if found
# use_2014 denotes whether or not we display in MiB vs MB
# round_to is the number of dedimal points to round our result to (0-15)
# strip_zeroes denotes whether we strip out zeroes
# True: Strip all 0s from the right of the decimal and remove decimal if needed
# False: Show the number as-is
# 0-10: Set the number of decimal places from 0 to 10
# Failsafe in case our size is unknown
if size == -1:
return "Unknown"
ext = ["B","KB","MB","GB","TB","PB"]
# Get our suffixes based on use_1024
ext = ["B","KiB","MiB","GiB","TiB","PiB"] if use_1024 else ["B","KB","MB","GB","TB","PB"]
div = 1024 if use_1024 else 1000
s = float(size)
s_dict = {}
# Iterate the ext list, and divide by 1000 each time
s_dict = {} # Initialize our dict
# Iterate the ext list, and divide by 1000 or 1024 each time to setup the dict {ext:val}
for e in ext:
s_dict[e] = s
s /= 1000
if suff and suff.upper() in s_dict:
# We supplied the suffix - use it \o/
bval = round(s_dict[suff.upper()], 2)
biggest = suff.upper()
else:
# Get the maximum >= 1 type
biggest = next((x for x in ext[::-1] if s_dict[x] >= 1), "B")
# Round to 2 decimal places
bval = round(s_dict[biggest], 2)
return "{:,.2f} {}".format(bval, biggest)
s /= div
# Get our suffix if provided - will be set to None if not found, or if started as None
suffix = next((x for x in ext if x.lower() == suffix.lower()),None) if suffix else suffix
# Get the largest value that's still over 1
biggest = suffix if suffix else next((x for x in ext[::-1] if s_dict[x] >= 1), "B")
# Determine our rounding approach - first make sure it's an int; default to 2 on error
try:round_to=int(round_to)
except:round_to=2
round_to = 0 if round_to < 0 else 15 if round_to > 15 else round_to # Ensure it's between 0 and 15
bval = round(s_dict[biggest], round_to)
# Split our number based on decimal points
a,b = str(bval).split(".")
# Check if we need to strip or pad zeroes
b = b.rstrip("0") if strip_zeroes else b.ljust(round_to,"0") if round_to > 0 else ""
return "{:,}{} {}".format(int(a),"" if not b else "."+b,biggest)
def _progress_hook(self, response, bytes_so_far, total_size):
if total_size > 0: