-
Notifications
You must be signed in to change notification settings - Fork 77
/
i18n.py
85 lines (67 loc) · 2.59 KB
/
i18n.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import logging
import formencode
import pylons
import pylons.i18n
from pylons.i18n import add_fallback, LanguageError, get_lang
from pylons.configuration import config
from pylons import session
from gettext import translation
log = logging.getLogger(__name__)
def setup_i18n():
"""Set languages from the request header and the session.
The session language(s) take priority over the request languages.
Automatically called by tg controllers to setup i18n.
Should only be manually called if you override controllers function.
"""
if pylons.session:
# If session is available, we try to see if there are languages set
languages = pylons.session.get(
config.get('lang_session_key', 'tg_lang'))
if languages:
if isinstance(languages, basestring):
languages = [languages]
else:
languages = []
else:
languages = []
languages.extend(pylons.request.accept_language.best_matches())
set_temporary_lang(languages)
def set_temporary_lang(languages):
"""Set the current language(s) used for translations without touching
the session language.
languages should be a string or a list of strings.
First lang will be used as main lang, others as fallbacks.
"""
# the logging to the screen was removed because
# the printing to the screen for every problem causes serious slow down.
try:
pylons.i18n.set_lang(languages)
except LanguageError:
pass
#log.warn("Language %s: not supported", languages)
try:
set_formencode_translation(languages)
except LanguageError:
pass
#log.warn("Language %s: not supported by FormEncode", languages)
def set_lang(languages, **kwargs):
"""Set the current language(s) used for translations
in current call and session.
languages should be a string or a list of strings.
First lang will be used as main lang, others as fallbacks.
"""
set_temporary_lang(languages)
if pylons.session:
session[config.get('lang_session_key', 'tg_lang')] = languages
session.save()
_localdir = formencode.api.get_localedir()
def set_formencode_translation(languages):
"""Set request specific translation of FormEncode."""
try:
formencode_translation = translation('FormEncode',languages=languages, localedir=_localdir)
except IOError, error:
raise LanguageError('IOError: %s' % error)
pylons.tmpl_context.formencode_translation = formencode_translation
__all__ = [
"setup_i18n", "set_lang", "get_lang", "add_fallback", "set_temporary_lang"
]