Ticket #8733: 8733-filesize-formats.diff
File 8733-filesize-formats.diff, 2.3 KB (added by , 16 years ago) |
---|
-
django/template/defaultfilters.py
7 7 except ImportError: 8 8 from django.utils.functional import wraps # Python 2.3, 2.4 fallback. 9 9 10 from django.utils.functional import curry 11 10 12 from django.template import Variable, Library 11 13 from django.conf import settings 12 14 from django.utils.translation import ugettext, ungettext … … 723 725 # MISC # 724 726 ################### 725 727 726 def filesizeformat(bytes):728 def __byte_size(bytes, base, unit, prefixes='KMGT'): 727 729 """ 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. 730 736 """ 731 737 try: 732 738 bytes = float(bytes) 733 739 except TypeError: 734 740 return u"0 bytes" 735 741 736 if bytes < 1024:742 if bytes < base: 737 743 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 = True744 744 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 752 filesizeformat = curry(__byte_size, base=1024, unit='B') 753 filesize = curry(__byte_size, base=1000, unit='B', prefixes='kMGT') 754 memorysize = curry(__byte_size, base=1024, unit='iB') 755 756 745 757 def pluralize(value, arg=u's'): 746 758 """ 747 759 Returns a plural suffix if the value is not 1. By default, 's' is used as … … 816 828 register.filter(escape) 817 829 register.filter(escapejs) 818 830 register.filter(filesizeformat) 831 register.filter(filesize) 832 register.filter(memorysize) 819 833 register.filter(first) 820 834 register.filter(fix_ampersands) 821 835 register.filter(floatformat)