- improved error reporting for undefined values by providing a position.
+- `filesizeformat` filter uses decimal prefixes now per default and can be
+ set to binary mode with the second parameter.
+
Version 2.0rc1
--------------
(no codename, released on June 9th 2008)
return environment.undefined('No random item, sequence was empty.')
-def do_filesizeformat(value):
+def do_filesizeformat(value, binary=False):
"""Format the value like a 'human-readable' file size (i.e. 13 KB,
- 4.1 MB, 102 bytes, etc).
+ 4.1 MB, 102 bytes, etc). Per default decimal prefixes are used (mega,
+ giga etc.), if the second parameter is set to `True` the binary
+ prefixes are (mebi, gibi).
"""
- # fail silently
- try:
- bytes = float(value)
- except TypeError:
- bytes = 0
-
- if bytes < 1024:
+ bytes = float(value)
+ base = binary and 1024 or 1000
+ middle = binary and 'i' or ''
+ if bytes < base:
return "%d Byte%s" % (bytes, bytes != 1 and 's' or '')
- elif bytes < 1024 * 1024:
- return "%.1f KB" % (bytes / 1024)
- elif bytes < 1024 * 1024 * 1024:
- return "%.1f MB" % (bytes / (1024 * 1024))
- return "%.1f GB" % (bytes / (1024 * 1024 * 1024))
+ elif bytes < base * base:
+ return "%.1f K%sB" % (bytes / base, middle)
+ elif bytes < base * base * base:
+ return "%.1f M%sB" % (bytes / (base * base), middle)
+ return "%.1f G%sB" % (bytes / (base * base * base), middle)
def do_pprint(value, verbose=False):
{{ 1000|filesizeformat }}|\
{{ 1000000|filesizeformat }}|\
{{ 1000000000|filesizeformat }}|\
-{{ 1000000000000|filesizeformat }}'
+{{ 1000000000000|filesizeformat }}|\
+{{ 100|filesizeformat(true) }}|\
+{{ 1000|filesizeformat(true) }}|\
+{{ 1000000|filesizeformat(true) }}|\
+{{ 1000000000|filesizeformat(true) }}|\
+{{ 1000000000000|filesizeformat(true) }}'
FIRST = '''{{ foo|first }}'''
FLOAT = '''{{ "42"|float }}|{{ "ajsghasjgd"|float }}|{{ "32.32"|float }}'''
FORMAT = '''{{ "%s|%s"|format("a", "b") }}'''
def test_filesizeformat(env):
tmpl = env.from_string(FILESIZEFORMAT)
out = tmpl.render()
- assert out == '100 Bytes|1000 Bytes|976.6 KB|953.7 MB|931.3 GB'
+ assert out == (
+ '100 Bytes|1.0 KB|1.0 MB|1.0 GB|1000.0 GB|'
+ '100 Bytes|1000 Bytes|976.6 KiB|953.7 MiB|931.3 GiB'
+ )
def test_first(env):