Source code for tornado.locale

#!/usr/bin/env python# -*- coding: utf-8 -*-# Copyright 2009 Facebook## Licensed under the Apache License, Version 2.0 (the "License"); you may# not use this file except in compliance with the License. You may obtain# a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the# License for the specific language governing permissions and limitations# under the License."""Translation methods for generating localized strings.To load a locale and generate a translated string:: user_locale = tornado.locale.get("es_LA") print user_locale.translate("Sign out")`tornado.locale.get()` returns the closest matching locale, not necessarily thespecific locale you requested. You can support pluralization withadditional arguments to `~Locale.translate()`, e.g.:: people = [...] message = user_locale.translate( "%(list)s is online", "%(list)s are online", len(people)) print message % {"list": user_locale.list(people)}The first string is chosen if ``len(people) == 1``, otherwise the secondstring is chosen.Applications should call one of `load_translations` (which uses a simpleCSV format) or `load_gettext_translations` (which uses the ``.mo`` formatsupported by `gettext` and related tools). If neither method is called,the `Locale.translate` method will simply return the original string."""from__future__importabsolute_import,division,print_function,with_statementimportcodecsimportcsvimportdatetimefromioimportBytesIOimportnumbersimportosimportrefromtornadoimportescapefromtornado.logimportgen_logfromtornado.utilimportPY3fromtornado._locale_dataimportLOCALE_NAMES_default_locale="en_US"_translations={}# type: dict_supported_locales=frozenset([_default_locale])_use_gettext=FalseCONTEXT_SEPARATOR="\x04"

[docs]defget(*locale_codes):"""Returns the closest match for the given locale codes. We iterate over all given locale codes in order. If we have a tight or a loose match for the code (e.g., "en" for "en_US"), we return the locale. Otherwise we move to the next code in the list. By default we return ``en_US`` if no translations are found for any of the specified locales. You can change the default locale with `set_default_locale()`. """returnLocale.get_closest(*locale_codes)

[docs]defset_default_locale(code):"""Sets the default locale. The default locale is assumed to be the language used for all strings in the system. The translations loaded from disk are mappings from the default locale to the destination locale. Consequently, you don't need to create a translation file for the default locale. """global_default_localeglobal_supported_locales_default_locale=code_supported_locales=frozenset(list(_translations.keys())+[_default_locale])

[docs]defload_translations(directory,encoding=None):"""Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation files of the form ``LOCALE.csv``, e.g. ``es_GT.csv``. The CSV files should have two or three columns: string, translation, and an optional plural indicator. Plural indicators should be one of "plural" or "singular". A given string can have both singular and plural forms. For example ``%(name)s liked this`` may have a different verb conjugation depending on whether %(name)s is one name or a list of names. There should be two rows in the CSV file for that string, one with plural indicator "singular", and one "plural". For strings with no verbs that would change on translation, simply use "unknown" or the empty string (or don't include the column at all). The file is read using the `csv` module in the default "excel" dialect. In this format there should not be spaces after the commas. If no ``encoding`` parameter is given, the encoding will be detected automatically (among UTF-8 and UTF-16) if the file contains a byte-order marker (BOM), defaulting to UTF-8 if no BOM is present. Example translation ``es_LA.csv``:: "I love you","Te amo" "%(name)s liked this","A %(name)s les gustó esto","plural" "%(name)s liked this","A %(name)s le gustó esto","singular" .. versionchanged:: 4.3 Added ``encoding`` parameter. Added support for BOM-based encoding detection, UTF-16, and UTF-8-with-BOM. """global_translationsglobal_supported_locales_translations={}forpathinos.listdir(directory):ifnotpath.endswith(".csv"):continuelocale,extension=path.split(".")ifnotre.match("[a-z]+(_[A-Z]+)?$",locale):gen_log.error("Unrecognized locale %r (path: %s)",locale,os.path.join(directory,path))continuefull_path=os.path.join(directory,path)ifencodingisNone:# Try to autodetect encoding based on the BOM.withopen(full_path,'rb')asf:data=f.read(len(codecs.BOM_UTF16_LE))ifdatain(codecs.BOM_UTF16_LE,codecs.BOM_UTF16_BE):encoding='utf-16'else:# utf-8-sig is "utf-8 with optional BOM". It's discouraged# in most cases but is common with CSV files because Excel# cannot read utf-8 files without a BOM.encoding='utf-8-sig'ifPY3:# python 3: csv.reader requires a file open in text mode.# Force utf8 to avoid dependence on $LANG environment variable.f=open(full_path,"r",encoding=encoding)else:# python 2: csv can only handle byte strings (in ascii-compatible# encodings), which we decode below. Transcode everything into# utf8 before passing it to csv.reader.f=BytesIO()withcodecs.open(full_path,"r",encoding=encoding)asinfile:f.write(escape.utf8(infile.read()))f.seek(0)_translations[locale]={}fori,rowinenumerate(csv.reader(f)):ifnotroworlen(row)<2:continuerow=[escape.to_unicode(c).strip()forcinrow]english,translation=row[:2]iflen(row)>2:plural=row[2]or"unknown"else:plural="unknown"ifpluralnotin("plural","singular","unknown"):gen_log.error("Unrecognized plural indicator %r in %s line %d",plural,path,i+1)continue_translations[locale].setdefault(plural,{})[english]=translationf.close()_supported_locales=frozenset(list(_translations.keys())+[_default_locale])gen_log.debug("Supported locales: %s",sorted(_supported_locales))

[docs]defget_supported_locales():"""Returns a list of all the supported locale codes."""return_supported_locales

[docs]classLocale(object):"""Object representing a locale. After calling one of `load_translations` or `load_gettext_translations`, call `get` or `get_closest` to get a Locale object. """@classmethod

[docs]defget_closest(cls,*locale_codes):"""Returns the closest match for the given locale code."""forcodeinlocale_codes:ifnotcode:continuecode=code.replace("-","_")parts=code.split("_")iflen(parts)>2:continueeliflen(parts)==2:code=parts[0].lower()+"_"+parts[1].upper()ifcodein_supported_locales:returncls.get(code)ifparts[0].lower()in_supported_locales:returncls.get(parts[0].lower())returncls.get(_default_locale)

@classmethod

[docs]defget(cls,code):"""Returns the Locale for the given locale code. If it is not supported, we raise an exception. """ifnothasattr(cls,"_cache"):cls._cache={}ifcodenotincls._cache:assertcodein_supported_localestranslations=_translations.get(code,None)iftranslationsisNone:locale=CSVLocale(code,{})elif_use_gettext:locale=GettextLocale(code,translations)else:locale=CSVLocale(code,translations)cls._cache[code]=localereturncls._cache[code]

[docs]deftranslate(self,message,plural_message=None,count=None):"""Returns the translation for the given message for this locale. If ``plural_message`` is given, you must also provide ``count``. We return ``plural_message`` when ``count != 1``, and we return the singular form for the given message when ``count == 1``. """raiseNotImplementedError()

[docs]defformat_date(self,date,gmt_offset=0,relative=True,shorter=False,full_format=False):"""Formats the given date (which should be GMT). By default, we return a relative time (e.g., "2 minutes ago"). You can return an absolute date string with ``relative=False``. You can force a full format date ("July 10, 1980") with ``full_format=True``. This method is primarily intended for dates in the past. For dates in the future, we fall back to full format. """ifisinstance(date,numbers.Real):date=datetime.datetime.utcfromtimestamp(date)now=datetime.datetime.utcnow()ifdate>now:ifrelativeand(date-now).seconds<60:# Due to click skew, things are some things slightly# in the future. Round timestamps in the immediate# future down to now in relative mode.date=nowelse:# Otherwise, future dates always use the full format.full_format=Truelocal_date=date-datetime.timedelta(minutes=gmt_offset)local_now=now-datetime.timedelta(minutes=gmt_offset)local_yesterday=local_now-datetime.timedelta(hours=24)difference=now-dateseconds=difference.secondsdays=difference.days_=self.translateformat=Noneifnotfull_format:ifrelativeanddays==0:ifseconds<50:return_("1 second ago","%(seconds)d seconds ago",seconds)%{"seconds":seconds}ifseconds<50*60:minutes=round(seconds/60.0)return_("1 minute ago","%(minutes)d minutes ago",minutes)%{"minutes":minutes}hours=round(seconds/(60.0*60))return_("1 hour ago","%(hours)d hours ago",hours)%{"hours":hours}ifdays==0:format=_("%(time)s")elifdays==1andlocal_date.day==local_yesterday.dayand \
relative:format=_("yesterday")ifshorterelse \
_("yesterday at %(time)s")elifdays<5:format=_("%(weekday)s")ifshorterelse \
_("%(weekday)s at %(time)s")elifdays<334:# 11mo, since confusing for same month last yearformat=_("%(month_name)s%(day)s")ifshorterelse \
_("%(month_name)s%(day)s at %(time)s")ifformatisNone:format=_("%(month_name)s%(day)s, %(year)s")ifshorterelse \
_("%(month_name)s%(day)s, %(year)s at %(time)s")tfhour_clock=self.codenotin("en","en_US","zh_CN")iftfhour_clock:str_time="%d:%02d"%(local_date.hour,local_date.minute)elifself.code=="zh_CN":str_time="%s%d:%02d"%((u'\u4e0a\u5348',u'\u4e0b\u5348')[local_date.hour>=12],local_date.hour%12or12,local_date.minute)else:str_time="%d:%02d%s"%(local_date.hour%12or12,local_date.minute,("am","pm")[local_date.hour>=12])returnformat%{"month_name":self._months[local_date.month-1],"weekday":self._weekdays[local_date.weekday()],"day":str(local_date.day),"year":str(local_date.year),"time":str_time}

[docs]defformat_day(self,date,gmt_offset=0,dow=True):"""Formats the given date as a day of week. Example: "Monday, January 22". You can remove the day of week with ``dow=False``. """local_date=date-datetime.timedelta(minutes=gmt_offset)_=self.translateifdow:return_("%(weekday)s, %(month_name)s%(day)s")%{"month_name":self._months[local_date.month-1],"weekday":self._weekdays[local_date.weekday()],"day":str(local_date.day),}else:return_("%(month_name)s%(day)s")%{"month_name":self._months[local_date.month-1],"day":str(local_date.day),}

[docs]deflist(self,parts):"""Returns a comma-separated list for the given list of parts. The format is, e.g., "A, B and C", "A and B" or just "A" for lists of size 1. """_=self.translateiflen(parts)==0:return""iflen(parts)==1:returnparts[0]comma=u' \u0648 'ifself.code.startswith("fa")elseu", "return_("%(commas)s and %(last)s")%{"commas":comma.join(parts[:-1]),"last":parts[len(parts)-1],}

[docs]deffriendly_number(self,value):"""Returns a comma-separated number for the given integer."""ifself.codenotin("en","en_US"):returnstr(value)value=str(value)parts=[]whilevalue:parts.append(value[-3:])value=value[:-3]return",".join(reversed(parts))

[docs]classCSVLocale(Locale):"""Locale implementation using tornado's CSV translation format."""deftranslate(self,message,plural_message=None,count=None):ifplural_messageisnotNone:assertcountisnotNoneifcount!=1:message=plural_messagemessage_dict=self.translations.get("plural",{})else:message_dict=self.translations.get("singular",{})else:message_dict=self.translations.get("unknown",{})returnmessage_dict.get(message,message)defpgettext(self,context,message,plural_message=None,count=None):ifself.translations:gen_log.warning('pgettext is not supported by CSVLocale')returnself.translate(message,plural_message,count)

[docs]classGettextLocale(Locale):"""Locale implementation using the `gettext` module."""def__init__(self,code,translations):try:# python 2self.ngettext=translations.ungettextself.gettext=translations.ugettextexceptAttributeError:# python 3self.ngettext=translations.ngettextself.gettext=translations.gettext# self.gettext must exist before __init__ is called, since it# calls into self.translatesuper(GettextLocale,self).__init__(code,translations)deftranslate(self,message,plural_message=None,count=None):ifplural_messageisnotNone:assertcountisnotNonereturnself.ngettext(message,plural_message,count)else:returnself.gettext(message)