Package turbogears :: Package i18n :: Module tg_gettext

Source Code for Module turbogears.i18n.tg_gettext

  1  import os 
  2  import sys 
  3  import logging 
  4   
  5  from gettext import translation 
  6   
  7  from turbojson.jsonify import jsonify 
  8   
  9  from turbogears import config 
 10  from turbogears.util import get_package_name, request_available 
 11  from turbogears.i18n.utils import get_locale 
 12   
 13  try: 
 14      from turbogears.i18n.sogettext import so_gettext 
 15  except ImportError: 
 16      so_gettext = None 
 17  try: 
 18      from turbogears.i18n.sagettext import sa_gettext 
 19  except ImportError: 
 20      sa_gettext = None 
 21   
 22  log = logging.getLogger('turbogears.i18n') 
 23   
 24   
 25  _catalogs = {} 
26 27 28 -def get_locale_dir():
29 localedir = config.get('i18n.locale_dir') 30 31 if not localedir: 32 package = get_package_name() 33 if package: 34 localedir = os.path.join(os.path.dirname( 35 sys.modules[package].__path__[0]), 'locales') 36 37 return localedir
38
39 40 -def is_locale_supported(locale, domain=None):
41 """Check if [domain].mo file exists for this language.""" 42 if not domain: 43 domain = config.get('i18n.domain', 'messages') 44 45 localedir = get_locale_dir() 46 return localedir and os.path.exists(os.path.join( 47 localedir, locale, 'LC_MESSAGES', '%s.mo' % domain))
48
49 50 -def get_catalog(locale, domain=None):
51 """Return translations for given locale.""" 52 if not domain: 53 domain = config.get('i18n.domain', 'messages') 54 55 catalog = _catalogs.setdefault(domain, {}) 56 57 try: 58 messages = catalog[locale] 59 except KeyError: 60 localedir = get_locale_dir() 61 languages = [locale] 62 if len(locale) > 2: 63 languages.append(locale[:2]) 64 try: 65 messages = translation(domain=domain, 66 localedir=localedir, languages=languages) 67 except (KeyError, IOError): 68 log.debug("Could not get translations for %s", languages) 69 messages = None 70 catalog[locale] = messages 71 72 return messages
73
74 75 -def plain_gettext(key, locale=None, domain=None):
76 """Get the gettext value for key. 77 78 Added to builtins as '_'. Returns Unicode string. 79 80 @param key: text to be translated 81 @param locale: locale code to be used. 82 If locale is None, gets the value provided by get_locale. 83 84 """ 85 func_name = config.get('i18n.gettext', 'tg_gettext') 86 gettext_func = dict(tg_gettext=tg_gettext, 87 so_gettext=so_gettext, sa_gettext=sa_gettext).get(func_name) 88 if gettext_func: 89 # gettext function exists, use it :) 90 return gettext_func(key, locale, domain) 91 else: 92 log.error("Translation disabled" 93 " - i18n.gettext function %s not available", gettext_func) 94 # gettext function could not be loaded? 95 # Just avoid to translate and return original data. 96 return key
97
98 99 -def tg_gettext(key, locale=None, domain=None):
100 """Get the gettext value for key. 101 102 Added to builtins as '_'. Returns Unicode string. 103 104 @param key: text to be translated 105 @param locale: locale code to be used. 106 If locale is None, gets the value provided by get_locale. 107 108 """ 109 if locale is None: 110 locale = get_locale() 111 112 if key: 113 messages = get_catalog(locale, domain) 114 if messages: 115 key = messages.ugettext(key) 116 117 return key
118
119 120 -def plain_ngettext(key1, key2, num, locale=None):
121 """Translate two possible texts based on whether num is greater than 1. 122 123 @param key1: text if num == 1 124 @param key2: text if num != 1 125 @param num: a number 126 @type num: integer 127 @locale: locale code to be used. 128 If locale is None, gets the value provided by get_locale. 129 130 """ 131 if num == 1: 132 key = key1 133 else: 134 key = key2 135 return plain_gettext(key, locale)
136
137 138 -class lazystring(object):
139 """Has a number of lazily evaluated functions replicating a string. 140 141 Just override the eval() method to produce the actual value. 142 143 """ 144
145 - def __init__(self, func, *args, **kw):
146 self.func = func 147 self.args = args 148 self.kw = kw
149
150 - def eval(self):
151 return self.func(*self.args, **self.kw)
152
153 - def __unicode__(self):
154 return unicode(self.eval())
155
156 - def __str__(self):
157 return str(self.eval())
158
159 - def __mod__(self, other):
160 return self.eval() % other
161
162 - def __cmp__(self, other):
163 return cmp(self.eval(), other)
164
165 - def __eq__(self, other):
166 return self.eval() == other
167
168 - def __deepcopy__(self, memo):
169 return self
170
171 172 -def lazify(func):
173 174 def newfunc(*args, **kw): 175 return lazystring(func, *args, **kw)
176 177 return newfunc 178
179 180 @jsonify.when("isinstance(obj, lazystring)") 181 -def jsonify_lazystring(obj):
182 return unicode(obj)
183 184 lazy_gettext = lazify(plain_gettext) 185 lazy_ngettext = lazify(plain_ngettext)
186 187 188 -def gettext(key, locale=None, domain=None):
189 """Get the gettext value for key. 190 191 Added to builtins as '_'. Returns Unicode string. 192 193 @param key: text to be translated 194 @param locale: locale code to be used. 195 If locale is None, gets the value provided by get_locale. 196 197 """ 198 return (request_available() and plain_gettext or lazy_gettext)( 199 key, locale, domain)
200
201 202 -def ngettext(key1, key2, num, locale=None):
203 """Translate two possible texts based on whether num is greater than 1. 204 205 @param key1: text if num==1 206 @param key2: text if num!=1 207 @param num: a number 208 @type num: integer 209 @param locale: locale code to be used. 210 If locale is None, gets the value provided by get_locale. 211 212 """ 213 return (request_available() and plain_ngettext or lazy_ngettext)( 214 key1, key2, num, locale)
215
216 217 -def install():
218 """Add the gettext function to __builtins__ as '_'.""" 219 __builtins__['_'] = gettext
220