Skip to content
Myr

Fixed filesizeformat filter. It should now conform to the official SI prefixes and use the correct prefixes for sizes greater than base ** 4.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Alan Plum · committed by Armin Ronacher · parent 4b37694 · Browse files · 1 file+24 added−12 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Signed-off-by: Armin Ronacher <armin.ronacher@active-4.com>

Diff stats

1 file+24 added−12 removed

  • other:+24 added−12 removed

1 file+24 added−12 removed

modified:jinja2/filters.py+24 added-12 removed
336 unmodified lines
337 return environment.undefined('No random item, sequence was empty.')338339340def do_filesizeformat(value, binary=False):341 """Format the value like a 'human-readable' file size (i.e. 13 KB,342 4.1 MB, 102 bytes, etc). Per default decimal prefixes are used (mega,343 giga, etc.), if the second parameter is set to `True` the binary344 prefixes are used (mebi, gibi).341 """Format the value like a 'human-readable' file size (i.e. 13 kB,342 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,343 Giga, etc.), if the second parameter is set to `True` the binary344 prefixes are used (Mebi, Gibi).345 """346 bytes = float(value)347 base = binary and 1024 or 1000348 middle = binary and 'i' or ''349 if bytes < base:350 return "%d Byte%s" % (bytes, bytes != 1 and 's' or '')351 elif bytes < base * base:352 return "%.1f K%sB" % (bytes / base, middle)353 elif bytes < base * base * base:354 return "%.1f M%sB" % (bytes / (base * base), middle)355 return "%.1f G%sB" % (bytes / (base * base * base), middle)348 prefixes = [349 (binary and "KiB" or "kB"),350 (binary and "MiB" or "MB"),351 (binary and "GiB" or "GB"),352 (binary and "TiB" or "TB"),353 (binary and "PiB" or "PB"),354 (binary and "EiB" or "EB"),355 (binary and "ZiB" or "ZB"),356 (binary and "YiB" or "YB")357 ]358 if bytes == 1:359 return "1 Byte"360 elif bytes < base:361 return "%d Bytes" % bytes362 else:363 for i, prefix in enumerate(prefixes):364 unit = base * base ** (i + 1)365 if bytes < unit:366 return "%.1f %s" % ((bytes / unit), prefix)367 return "%.1f %s" % ((bytes / unit), prefix)368369370def do_pprint(value, verbose=False):371 """Pretty print a variable. Useful for debugging.
430 unmodified lines