Package turbogears :: Package i18n :: Module format

Source Code for Module turbogears.i18n.format

  1  """Localized formatting functions. 
  2   
  3  These functions extract localization data from config files located 
  4  in the data/directory. 
  5   
  6  """ 
  7   
  8  import os 
  9  import re 
 10  from operator import itemgetter 
 11  from warnings import filterwarnings 
 12   
 13  import pkg_resources 
 14   
 15  from turbogears.i18n.utils import get_locale 
 16   
 17  try: 
 18      # locale modules can have same name as locale directories 
 19      filterwarnings('ignore', message="Not importing directory", 
 20          category=ImportWarning, module='turbogears.i18n') 
 21  except NameError: # Python < 2.5 
 22      pass # does not have ImportWarning anyway 
 23   
 24   
25 -def is_locale_format(locale):
26 """Check if locale is supported.""" 27 py_filename = pkg_resources.resource_filename( 28 'turbogears.i18n.data', '%s.py' % locale) 29 if os.path.exists(py_filename): 30 return True 31 pyc_filename = pkg_resources.resource_filename( 32 'turbogears.i18n.data', '%s.pyc' % locale) 33 if os.path.exists(pyc_filename): 34 return True 35 return False
36 37
38 -def get_locale_module(locale):
39 """Get i18n module supporting the locale.""" 40 try: 41 # check if locale is supported. If not, check again with 42 # first part of locale for example, 'fi_FI' > 'fi'. 43 if not is_locale_format(locale): 44 locale = locale[:2] 45 name = 'turbogears.i18n.data.%s' % locale 46 mod = __import__(name) 47 parts = name.split('.')[1:] 48 for p in parts: 49 mod = getattr(mod, p) 50 return mod 51 except (ImportError, AttributeError): 52 return None
53 54
55 -def get(locale, name, default=None):
56 """Get an attribute value for the locale.""" 57 locale = get_locale(locale) 58 mod = get_locale_module(locale) 59 return getattr(mod, name, default)
60 61
62 -def get_countries(locale=None):
63 """Get all supported countries. 64 65 Returns a list of tuples, consisting of international country code 66 and localized name, e.g. ('AU', 'Australia'). 67 68 """ 69 countries = get(locale, 'countries', {}).items() 70 countries.sort(key=itemgetter(1)) 71 return countries
72 73
74 -def get_country(key, locale=None):
75 """Get localized name of country based on international country code.""" 76 return get(locale, 'countries', {})[key]
77 78
79 -def get_languages(locale=None):
80 """Get all supported languages. 81 82 Returns a list of tuples, with language code and localized name, 83 e.g. ('en', 'English'). 84 85 """ 86 languages = get(locale, 'languages', {}).items() 87 languages.sort(key=itemgetter(1)) 88 return languages
89 90
91 -def get_language(key, locale=None):
92 """Get localized name of language based on language code.""" 93 return get(locale, 'languages', {})[key]
94 95
96 -def get_month_names(locale=None):
97 """Get list of full month names, starting with January.""" 98 return get(locale, 'months', [])
99 100
101 -def get_abbr_month_names(locale=None):
102 """Get list of abbreviated month names, starting with Jan.""" 103 return get(locale, 'abbrMonths', [])
104 105
106 -def get_weekday_names(locale=None):
107 """Get list of full weekday names.""" 108 return get(locale, 'days', [])
109 110
111 -def get_abbr_weekday_names(locale=None):
112 """Get list of abbreviated weekday names.""" 113 return get(locale, 'abbrDays', get_weekday_names(locale))
114 115
116 -def get_decimal_format(locale=None):
117 """Get decimal point for the locale.""" 118 return get(locale, 'numericSymbols', {}).get('decimal', '.')
119 120
121 -def get_group_format(locale=None):
122 """Get digit group separator for thousands for the locale.""" 123 return get(locale, 'numericSymbols', {}).get('group', ',')
124 125
126 -def format_number(value, locale=None):
127 """Get number formatted with grouping for thousands. 128 129 E.g. 5000000 will be formatted as 5,000,000. 130 131 """ 132 gf = get_group_format(locale) 133 thou = re.compile(r'([0-9])([0-9][0-9][0-9]([%s]|$))' % gf).search 134 v = str(value) 135 mo = thou(v) 136 while mo is not None: 137 i = mo.start(0) 138 v = v[:i+1] + gf + v[i+1:] 139 mo = thou(v) 140 return unicode(v)
141 142
143 -def format_decimal(value, num_places, locale=None):
144 """Get number formatted with grouping for thousands and decimal places. 145 146 E.g. 5000000.898 will be formatted as 5,000,000.898. 147 148 """ 149 v = ('%%.%df' % num_places) % value 150 if num_places == 0: 151 return format_number(v, locale=locale) 152 num, decimals = v.split('.', 1) 153 return format_number(num, locale) + unicode( 154 get_decimal_format(locale) + decimals)
155 156
157 -def format_currency(value, locale=None):
158 """Get formatted currency value.""" 159 return format_decimal(value, 2, locale)
160 161
162 -def parse_number(value, locale=None):
163 """Take localized number string and return a long integer. 164 165 Throws ValueError if bad format. 166 167 """ 168 return long(value.replace(get_group_format(locale), ""))
169 170
171 -def parse_decimal(value, locale=None):
172 """Take localized decimal string and return a float. 173 174 Throws ValueError if bad format. 175 176 """ 177 value = value.replace(get_group_format(locale), '') 178 value = value.replace(get_decimal_format(locale), '.') 179 return float(value)
180 181
182 -def get_date_format(format, locale=None):
183 """Get localized date format.""" 184 formats = get(locale, 'dateFormats', {}) 185 return formats.get(format, None)
186 187
188 -def format_date(dt, format='medium', locale=None, 189 time_format='', date_format=''):
190 """Get formatted date value. 191 192 format can be "full", "long", "medium" or "short". 193 To have complete control over formatting, 194 use time_format and date_format parameters. 195 196 @param dt: datetime 197 @type dt: datetime.datetime 198 199 @param format: format('full', 'long', 'medium', 'short') 200 @type format: string 201 202 @param locale: the locale 203 @type locale: string 204 205 @param time_format: standard time formatting string, e.g. %H:%M 206 @type time_format:s tring 207 208 @param time_format: date formatting template string. 209 Template variables include standard date formatting string like %d or %Y 210 plus a few locale-specific names: 211 %%(abbrmonthname)s, %%(dayname)s, %%(abbrmonthname)s and %%(monthname)s. 212 @type time_format: string 213 214 """ 215 pattern = date_format or get_date_format(format, locale) 216 if not pattern: 217 return str(dt) 218 month = dt.month - 1 219 weekday = dt.weekday() 220 # becasue strftime() accepts str only but not unicode, 221 # we encode string to utf-8 and then decode back 222 date_str = dt.strftime(pattern.encode('utf8') + time_format) 223 return date_str.decode('utf8') % dict( 224 monthname=get_month_names(locale)[month], 225 abbrmonthname=get_abbr_month_names(locale)[month], 226 dayname=get_weekday_names(locale)[weekday], 227 abbrdayname=get_abbr_weekday_names(locale)[weekday])
228