Ticket #8733: 8733-filesize-formats.diff

File 8733-filesize-formats.diff, 2.3 KB (added by Daniel Pope <dan@…>, 16 years ago)

Implementation for all three byte size schemes

  • django/template/defaultfilters.py

     
    77except ImportError:
    88    from django.utils.functional import wraps  # Python 2.3, 2.4 fallback.
    99
     10from django.utils.functional import curry
     11
    1012from django.template import Variable, Library
    1113from django.conf import settings
    1214from django.utils.translation import ugettext, ungettext
     
    723725# MISC            #
    724726###################
    725727
    726 def filesizeformat(bytes):
     728def __byte_size(bytes, base, unit, prefixes='KMGT'):
    727729    """
    728     Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
    729     102 bytes, etc).
     730    Formats the data size in bytes as a human-readable value.
     731   
     732    Because there are different schemes used in for this formatting in different
     733    situations, this is generalised: the most suitable power of 'base' is found
     734    and the value is displayed to 1 decimal place, with the corresponding prefix
     735    and unit as given.
    730736    """
    731737    try:
    732738        bytes = float(bytes)
    733739    except TypeError:
    734740        return u"0 bytes"
    735741
    736     if bytes < 1024:
     742    if bytes < base:
    737743        return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
    738     if bytes < 1024 * 1024:
    739         return ugettext("%.1f KB") % (bytes / 1024)
    740     if bytes < 1024 * 1024 * 1024:
    741         return ugettext("%.1f MB") % (bytes / (1024 * 1024))
    742     return ugettext("%.1f GB") % (bytes / (1024 * 1024 * 1024))
    743 filesizeformat.is_safe = True
    744744
     745    cbase = 1
     746    for prefix in prefixes:
     747        cbase *= base
     748        if bytes < (cbase * base):
     749            break
     750    return "%.1f %s%s" % (bytes / cbase, prefix, unit)
     751
     752filesizeformat = curry(__byte_size, base=1024, unit='B')
     753filesize = curry(__byte_size, base=1000, unit='B', prefixes='kMGT')
     754memorysize = curry(__byte_size, base=1024, unit='iB')
     755
     756
    745757def pluralize(value, arg=u's'):
    746758    """
    747759    Returns a plural suffix if the value is not 1. By default, 's' is used as
     
    816828register.filter(escape)
    817829register.filter(escapejs)
    818830register.filter(filesizeformat)
     831register.filter(filesize)
     832register.filter(memorysize)
    819833register.filter(first)
    820834register.filter(fix_ampersands)
    821835register.filter(floatformat)
Back to Top