Ticket #14002: bigger-filesizeformat.2.diff

File bigger-filesizeformat.2.diff, 1.7 KB (added by Aaron T. Myers, 14 years ago)

New version with tests and addressing review comment.

  • django/template/defaultfilters.py

     
    803803    except (TypeError,ValueError,UnicodeDecodeError):
    804804        return u"0 bytes"
    805805
    806     if bytes < 1024:
     806    BYTE_UNITS = (
     807        ('KB', 1024),
     808        ('MB', 1024 * 1024),
     809        ('GB', 1024 * 1024 * 1024),
     810        ('TB', 1024 * 1024 * 1024 * 1024),
     811        ('PB', 1024 * 1024 * 1024 * 1024 * 1024)
     812    )
     813
     814    if bytes < BYTE_UNITS[0][1]:
    807815        return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
    808     if bytes < 1024 * 1024:
    809         return ugettext("%.1f KB") % (bytes / 1024)
    810     if bytes < 1024 * 1024 * 1024:
    811         return ugettext("%.1f MB") % (bytes / (1024 * 1024))
    812     return ugettext("%.1f GB") % (bytes / (1024 * 1024 * 1024))
     816    for index, (unit, unit_size) in enumerate(BYTE_UNITS):
     817        if bytes < unit_size * 1024 or index == len(BYTE_UNITS) - 1:
     818            return ugettext("%.1f %s") % (bytes / unit_size, unit)
    813819filesizeformat.is_safe = True
    814820
    815821def pluralize(value, arg=u's'):
  • tests/regressiontests/defaultfilters/tests.py

     
    476476>>> filesizeformat(1024*1024*1024)
    477477u'1.0 GB'
    478478
     479>>> filesizeformat(1024*1024*1024*1024)
     480u'1.0 TB'
     481
     482>>> filesizeformat(1024*1024*1024*1024*1024)
     483u'1.0 PB'
     484
     485>>> filesizeformat(1024*1024*1024*1024*1024*2000)
     486u'2000.0 PB'
     487
    479488>>> filesizeformat(complex(1,-1))
    480489u'0 bytes'
    481490
Back to Top