Package turbogears :: Package i18n :: Module utils

Source Code for Module turbogears.i18n.utils

  1  """General i18n utility functions.""" 
  2   
  3  import urllib 
  4   
  5  try: 
  6      import json 
  7  except ImportError: # Python < 2.6 
  8      import simplejson as json 
  9  import cherrypy 
 10   
 11  from turbogears import config 
 12  from turbogears.release import version as tg_version 
 13  from turbogears.util import parse_http_accept_header, request_available 
 14   
 15   
16 -class TGURLopener(urllib.FancyURLopener):
17 version = 'TurboGears/%s' % tg_version
18 19
20 -def google_translate(from_lang, to_lang, text):
21 """Translate text via the translate.google.com service. 22 23 The source language is given by 'from_lang' and the target language as 24 'to_lang'. 'text' must be a unicode or UTF-8 encoded string. 25 26 """ 27 if isinstance(text, unicode): 28 has_nbsp = u'\xa0' in text 29 text = text.encode('utf-8') 30 else: 31 has_nbsp = False 32 params = urllib.urlencode(dict(v='1.0', 33 langpair='%s|%s' % (from_lang, to_lang), q=text)) 34 try: 35 result = TGURLopener().open('http://ajax.googleapis.com' 36 '/ajax/services/language/translate', params).read() 37 except IOError: 38 text = None 39 else: 40 try: 41 result = json.loads(result) 42 except ValueError: 43 text = None 44 else: 45 try: 46 text = result['responseData']['translatedText'] 47 except (KeyError, TypeError): 48 text = None 49 else: 50 if text and not has_nbsp: 51 text = text.replace(u'\xa0', ' ') 52 return text
53 54
55 -def lang_in_gettext_format(lang):
56 if len(lang) > 2: 57 country = lang[3:].upper() 58 lang = lang[:2] + '_' + country 59 return lang
60 61
62 -def get_accept_languages(accept):
63 """Get the list of accepted languages, by order of preference. 64 65 THis is based on the HTTP Accept-Language string. See W3C RFC 2616 66 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) for specification. 67 68 """ 69 langs = parse_http_accept_header(accept) 70 for index, lang in enumerate(langs): 71 langs[index] = lang_in_gettext_format(lang) 72 return langs
73 74
75 -def get_locale(locale=None):
76 """Get the user locale. 77 78 This is done using _get_locale or an app-specific locale lookup function. 79 80 """ 81 if not locale: 82 get_locale_f = config.get('i18n.get_locale', _get_locale) 83 locale = get_locale_f() 84 return locale
85 86
87 -def _get_locale():
88 """Default function for returning the locale. 89 90 First it looks in the session for a locale key, then it checks the HTTP 91 Accept-Language header, and finally it checks the config default locale 92 setting. This can be replaced by your own function by setting the CherryPy 93 config setting i18n.get_locale to your function name. 94 95 """ 96 if not request_available(): 97 return config.get('i18n.default_locale', 'en') 98 99 if config.get('tools.sessions.on', False): 100 session_key = config.get('i18n.session_key', 'locale') 101 locale = cherrypy.session.get(session_key) 102 if locale: 103 return locale 104 browser_accept_lang = _get_locale_from_accept_header() 105 return browser_accept_lang or config.get('i18n.default_locale', 'en')
106 107
108 -def _get_locale_from_accept_header():
109 """Check HTTP Accept-Language header to find the preferred language.""" 110 try: 111 header = cherrypy.request.headers.get('Accept-Language') 112 if header: 113 accept_languages = get_accept_languages(header) 114 if accept_languages: 115 return accept_languages[0] 116 except AttributeError: 117 pass
118 119
120 -def set_session_locale(locale):
121 """Set the i18n session locale. 122 123 Raises an error if session support is not enabled. 124 125 """ 126 session_key = config.get('i18n.session_key', 'locale') 127 cherrypy.session[session_key] = locale
128