-
Couldn't load subscription status.
- Fork 5.5k
Open
Labels
Description
The tornado.locale.Locale.get_closest() (and as such by extension tornado.locale.get) function is a bit malformed. It tries to match two character language codes directly against the frozenset in which the five character language codes are stored, which obviously fails. As a result it can only get exact matches and will return the default locale when using two character codes.
@classmethod
def get_closest(cls, *locale_codes):
"""Returns the closest match for the given locale code."""
for code in locale_codes:
if not code:
continue
code = code.replace("-", "_")
parts = code.split("_")
if len(parts) > 2:
continue
elif len(parts) == 2:
code = parts[0].lower() + "_" + parts[1].upper()
if code in _supported_locales:
return cls.get(code)
if parts[0].lower() in _supported_locales:
return cls.get(parts[0].lower())
return cls.get(_default_locale)
Specifically this part:
if parts[0].lower() in _supported_locales:
return cls.get(parts[0].lower())
I wrote the following simple function in my own code to bypass this problem but I bet someone else can write it a bit nicer into the intended function:
locale = self.request.headers.get('Accept-Language')
if locale:
for l in tornado.locale.get_supported_locales():
if locale == l.split("_")[0]:
self.locale = tornado.locale.get(l)