Module egg_translations :: Class EggTranslations
[hide private]

Class EggTranslations

source code

object --+
         |
        EggTranslations

Instance Methods [hide private]
 
__init__(self)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
source code
 
initialize(self, localeSet, iniFileName='resources.ini', encoding='UTF-8', fallback=True)
The initialize method performs the following operations:
source code
 
hasKey(self, project, name, locale=None)
returns True if a key was specified in one or more eggs resource ini files (default is "resource.ini") for the given project and name.
source code
 
getValueForKey(self, project, name, locale=None)
Returns the unicode string value that was specified in one or more eggs resource ini files (default is "resource.ini") for the given project and name.
source code
 
isDirectory(self, project, name, locale=None)
Returns True if:
source code
 
listDirectory(self, project, name, locale=None)
Returns a list of unicode values containing the names of files in the directory entry for the given project and name.
source code
 
hasResource(self, project, name, locale=None)
Returns True if:
source code
 
getResourceAsStream(self, project, name, locale=None)
Returns a file handle to the resource for the given project and name.
source code
 
getResourceAsLines(self, project, name, locale=None, encoding='UTF-8')
Returns a generator containing a list of non-blank non-comment lines in a resource file for the given project and name.
source code
 
getResourceAsString(self, project, name, locale=None, encoding='UTF-8')
Returns a unicode string containing the contents of the resource file for the given project and name.
source code
 
getText(self, project, name, txt, *args)
Returns a unicode string containing the localized value for key txt in the given project.
source code
 
hasFallback(self)
Returns True if fallback was set to True in either the EggTranslations.initialize method or the EggTranslations.setLocaleSet method.
source code
 
hasTranslation(self, project, name, locale)
returns True if the gettext mo file for the given locale, project, and name is loaded.
source code
 
getAvailableLocales(self, project)
Returns a list of the locales that have registered one or more key value pairs for the given project.
source code
 
getINIFileName(self)
Returns the unicode file name of the resource ini files.
source code
 
getLocaleSet(self)
Returns a list of valid str locale language / country codes.
source code
 
setLocaleSet(self, localeSet, fallback=True)
Resets the EggTranslations locale set list.
source code
 
normalizeLocale(self, locale)
Normalizes the str locale to lower case all lang codes and upper case all country codes.
source code
 
isValidLocaleForm(self, locale)
Returns True if the str locale passed has a valid form which is either lang code ("es") or lang code / country code ("es_UY").
source code
 
yieldFallbackLocales(self, localeSet)
Adds the lang code, if not already present, to the localeSet as a fallback to the lang country code.
source code
 
getDebugString(self)
Returns a str representation of the EggTranslations's egg loading values suitable for debugging using print, the logging package, or a UI dialog box.
source code
 
_parseINIFiles(self, dist)
Callback method passed to pkg_resources.add_activation_listener method.
source code
 
_getTupleForKey(self, project, name, locale=None) source code
 
_raiseNameError(self, project, name, locale) source code
 
_raiseParseError(self, dist, errTxt, *args) source code

Inherited from object: __delattr__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __str__

Class Variables [hide private]
  _NAME = 'EggTranslations'
Properties [hide private]
  _fallback
  _gtCache
  _iniCache
  _iniEncoding
  _iniFileName
  _init
  _localeCache
  _localeSet
  _moCache

Inherited from object: __class__

Method Details [hide private]

__init__(self)
(Constructor)

source code 
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
Overrides: object.__init__
(inherited documentation)

initialize(self, localeSet, iniFileName='resources.ini', encoding='UTF-8', fallback=True)

source code 
The initialize method performs the following operations:
  1. Calls the pkg_resources.add_activation_listener method passing the EggTranslations._parseINIFiles method as the callback. See the parseINIFiles method for more info on loading resources and gettext translation files.
  2. Calls the EggTranslations setLocaleSet method passing the localeSet param. See the setLocaleSet method documentation for more info.

The initialize method sets the locale set and loads the resource and translation caches.

It must be called before using the EggTranslations API.

The initialize method can only be called once per EggTranslations instance.
Parameters:
  • localeSet (ASCII str or unicode or list containing ASCII str or unicode values) - A unicode or str or list containing locale country and language codes. The value(s) must be able to be converted to ASCII.
  • iniFileName (ASCII str or unicode) - The name of the resource ini file in the egg's info directory.

    This file contains the location of localized and non-localized resources as well as translation files in gettext mo format. The default value for this file is "resources.ini". If a str is passed it must be able to be converted to unicode using the encoding passed to the initialize method. The default encoding is "UTF-8".
  • encoding (ASCII str or unicode) - The character set encoding of the iniFileName. This encoding will be used to convert str values contained in the iniFileName to unicode. The default encoding is "UTF-8".
  • fallback (boolean) - Indicates whether locale set fallback should take place. If set to True, the EggTranslations will search all locales in the locale set till a resource or gettext mo translation file is found. If set to False the EggTranslations will only try to locate a resource or gettext mo translation file for the current locale which is the first locale in the locale set.
Raises:

hasKey(self, project, name, locale=None)

source code 

returns True if a key was specified in one or more eggs resource ini files (default is "resource.ini") for the given project and name.

The locale is an optional argument. By default the locale set is searched in fallback order as well as the 'all' default locale (if fallback=True in the initialize or setLocaleSet method) until a key is found. If no key found the method returns False.

However, if a locale is specified the method will only search for a key in the resource ini files for the given locale.
Parameters:
  • project (ASCII str or unicode) - A project is a root namespace under which resources and localizations exist.

    A project name matches an egg name. An egg's info file can contain resource and localizations for more than one project.

    The project name must be either an ASCII str or unicode.
  • name (ASCII str or unicode) - name is the key to lookup in a resource ini file to retrieve the value specifed. For example, myname = this is my value.

    The name must be either an ASCII str or unicode.
  • locale (unicode or ASCII str) - Optional argument that if specified tells the method to only return True if key is present in one or more ini files for the given locale. This parameter if specified must contain a valid language / country locale i.e. "en_US" or "en"
Returns:
bool True if the name is found otherwise False
Raises:
  • UnicodeDecodeError -
  • UnicodeEncodeError -

getValueForKey(self, project, name, locale=None)

source code 

Returns the unicode string value that was specified in one or more eggs resource ini files (default is "resource.ini") for the given project and name. or None if not found.

The locale is an optional argument. By default the locale set is searched in fallback order (if fallback=True in the initialize or setLocale method) until a key is found.

However, if a locale is specified the method will only search for a key in the resource ini files for the given locale.

Example:

If you have a resource.ini file containing the following entry:
     [MyProject::fr]
      myimage = /resources/imgs/myimage.png
then:
  >>> print eggRMInstance.getValueForKey("MyProject",
  ...                               "myimage", "fr")
  /resource/imgs/myimage.png
Parameters:
  • project (ASCII str or unicode) - A project is a root namespace under which resources and localizations exist.

    A project name matches an egg name. An egg's info file can contain resource and localizations for more than one project.

    The project name must be either an ASCII str or unicode.
  • name (ASCII str or unicode) - name is the key to lookup in a resource ini file to retrieve the value specifed. For example, myname = this is my value.

    The name must be either an ASCII str or unicode.
  • locale (unicode or ASCII str) - Optional argument that if specified tells the method to only return True if key is present in one or more ini files for the given locale. This parameter if specified must contain a valid language / country locale i.e. "en_US" or "en"
Returns:
unicode value or None if not found
Raises:
  • UnicodeDecodeError -
  • UnicodeEncodeError -

isDirectory(self, project, name, locale=None)

source code 
Returns True if:
  1. One or more resource ini files have an entry for the key contained in the name parameter.
  2. The entry is a valid directory path.

The locale is an optional argument. By default the locale set is searched in fallback order (if fallback=True in the initialize or setLocale method) until a key is found. If no key found the method returns False.

However, if a locale is specified the method will only search for a key in the resource ini files for the given locale.
Parameters:
  • project (ASCII str or unicode) - A project is a root namespace under which resources and localizations exist.

    A project name matches an egg name. An egg's info file can contain resource and localizations for more than one project.

    The project name must be either an ASCII str or unicode.
  • name (ASCII str or unicode) - name is the key to lookup in a resource ini file to retrieve the value specifed. For example, myname = this is my value.

    The name must be either an ASCII str or unicode.
  • locale (unicode or ASCII str) - Optional argument that if specified tells the method to only return True if key is present in one or more ini files for the given locale. This parameter if specified must contain a valid language / country locale i.e. "en_US" or "en"
Returns:
bool True if the name is found and the entry for that name is a valid directory path in an egg otherwise False
Raises:
  • UnicodeDecodeError -
  • UnicodeEncodeError -

listDirectory(self, project, name, locale=None)

source code 

Returns a list of unicode values containing the names of files in the directory entry for the given project and name. The listDirectory method will not return the names of sub directories only files in the directory for the given project and name.

The locale is an optional argument. By default the locale set is searched in fallback order (if fallback=True in the initialize or setLocale method) until a key is found. If no key found the method returns False.

However, if a locale is specified the method will only search for a key in the resource ini files for the given locale.
Parameters:
  • project (ASCII str or unicode) - A project is a root namespace under which resources and localizations exist.

    A project name matches an egg name. An egg's info file can contain resource and localizations for more than one project.

    The project name must be either an ASCII str or unicode.
  • name (ASCII str or unicode) - name is the key to lookup in a resource ini file to retrieve the value specifed. For example, myname = this is my value.

    The name must be either an ASCII str or unicode.
  • locale (unicode or ASCII str) - Optional argument that if specified tells the method to only return True if key is present in one or more ini files for the given locale. This parameter if specified must contain a valid language / country locale i.e. "en_US" or "en"
Returns:
list of unicode filenames
Raises:
  • UnicodeDecodeError -
  • UnicodeEncodeError -
  • NameError -
  • OSError -

hasResource(self, project, name, locale=None)

source code 
Returns True if:
  1. one or more resource ini files have an entry for the key contained in the name parameter.
  2. The entry must be a valid path to a file in the same egg as resource ini.

Example:

If you have a resource.ini file containing the following entry:
       [MyProject::fr]
       myResource=/resources/myresource.png
then:
  >>> print eggRMInstance.hasResource("MyProject",
  ...                                 "myResource", "fr")
  True
Parameters:
  • project (ASCII str or unicode) - A project is a root namespace under which resources and localizations exist.

    A project name matches an egg name. An egg's info file can contain resource and localizations for more than one project.

    The project name must be either an ASCII str or unicode.
  • name (ASCII str or unicode) - name is the key to lookup in a resource ini file to retrieve the value specifed. For example, myname = this is my value.

    The name must be either an ASCII str or unicode.
  • locale (unicode or ASCII str) - Optional argument that if specified tells the method to only return True if key is present in one or more ini files for the given locale. This parameter if specified must contain a valid language / country locale i.e. "en_US" or "en"
Returns:
bool True if the name key points to at least one resource in an egg otherwise False.
Raises:
  • UnicodeDecodeError -
  • UnicodeEncodeError - The locale is an optional argument. By default the locale set is searched in fallback order (if fallback=True in the initialize or setLocale method) until a key is found. If no key found the method returns False.

    However, if a locale is specified the method will only search for a key in the resource ini files for the given locale.

getResourceAsStream(self, project, name, locale=None)

source code 

Returns a file handle to the resource for the given project and name.

The locale is an optional argument. By default the locale set is searched in fallback order (if fallback=True in the initialize or setLocale method) until a key is found. If no key found the method returns False.

However, if a locale is specified the method will only search for a key in the resource ini files for the given locale.
Parameters:
  • project (ASCII str or unicode) - A project is a root namespace under which resources and localizations exist.

    A project name matches an egg name. An egg's info file can contain resource and localizations for more than one project.

    The project name must be either an ASCII str or unicode.
  • name (ASCII str or unicode) - name is the key to lookup in a resource ini file to retrieve the value specifed. For example, myname = this is my value.

    The name must be either an ASCII str or unicode.
  • locale (unicode or ASCII str) - Optional argument that if specified tells the method to only return True if key is present in one or more ini files for the given locale. This parameter if specified must contain a valid language / country locale i.e. "en_US" or "en"
Returns:
file handle to the resource
Raises:
  • UnicodeDecodeError -
  • UnicodeEncodeError -
  • NameError -
  • IOError -

getResourceAsLines(self, project, name, locale=None, encoding='UTF-8')

source code 

Returns a generator containing a list of non-blank non-comment lines in a resource file for the given project and name.

The locale is an optional argument. By default the locale set is searched in fallback order (if fallback=True in the initialize or setLocale method) until a key is found. If no key found the method returns False.

However, if a locale is specified the method will only search for a key in the resource ini files for the given locale.
Parameters:
  • project (ASCII str or unicode) - A project is a root namespace under which resources and localizations exist.

    A project name matches an egg name. An egg's info file can contain resource and localizations for more than one project.

    The project name must be either an ASCII str or unicode.
  • name (ASCII str or unicode) - name is the key to lookup in a resource ini file to retrieve the value specifed. For example, myname = this is my value.

    The name must be either an ASCII str or unicode.
  • locale (unicode or ASCII str) - Optional argument that if specified tells the method to only return True if key is present in one or more ini files for the given locale. This parameter if specified must contain a valid language / country locale i.e. "en_US" or "en"
  • encoding (ASCII str or unicode) - The character set encoding of the resource file. This encoding will be used to convert str values contained in the file to unicode. The default encoding is "UTF-8".
Returns:
generator list of non-blank non-comment unicode lines.
Raises:
  • UnicodeDecodeError -
  • UnicodeEncodeError -
  • NameError -
  • IOError -
  • LookupError - Example:

    Imagine you have a resource.ini file that contains the following:
         [MyProject::all]
         myDocument = README.txt
    
    Then you might retrieve all lines from the ``README.txt`` file via:
       >>> lines = eggRMInstance.getResourceAsLines("MyProject",
       ...                                          "myDocument",
       ...                                          "all")
    
       >>> for line in lines:
       ...    print line
    

getResourceAsString(self, project, name, locale=None, encoding='UTF-8')

source code 

Returns a unicode string containing the contents of the resource file for the given project and name.

The locale is an optional argument. By default the locale set is searched in fallback order (if fallback=True in the initialize or setLocale method) until a key is found. If no key found the method returns False.

However, if a locale is specified the method will only search for a key in the resource ini files for the given locale.

Example:

If you have a resource.ini file containing the following entry:
     [MyProject::all]
     myDocument = README.txt
Then you could retrieve the entire contents of README.txt as a unicode string via:
  >>> f = eggRMInstance.getResourceAsString("MyProject",
  ...                                       "myDocument",
  ...                                       "all")

  >>> f
  u'This is the text contained in the readme file'
Parameters:
  • project (ASCII str or unicode) - A project is a root namespace under which resources and localizations exist.

    A project name matches an egg name. An egg's info file can contain resource and localizations for more than one project.

    The project name must be either an ASCII str or unicode.
  • name (ASCII str or unicode) - name is the key to lookup in a resource ini file to retrieve the value specifed. For example, myname = this is my value.

    The name must be either an ASCII str or unicode.
  • locale (unicode or ASCII str) - Optional argument that if specified tells the method to only return True if key is present in one or more ini files for the given locale. This parameter if specified must contain a valid language / country locale i.e. "en_US" or "en"
  • encoding (ASCII str or unicode) - The character set encoding of the resource file. This encoding will be used to convert str values contained in the file to unicode. The default encoding is "UTF-8".
Returns:
unicode contents of the resource file.
Raises:
  • UnicodeDecodeError -
  • UnicodeEncodeError -
  • NameError -
  • IOError -
  • LookupError -

getText(self, project, name, txt, *args)

source code 

Returns a unicode string containing the localized value for key txt in the given project. The name parameter points to a key in a resource ini file that contain a value entry pointing to a gettext .mo resource in the same egg.

An optional additional argument can be specified as the default value to return if no localized is found.

The txt parameter will be returned by EggTranslations.getText if no localized value found for the txt parameter.

However, if the default value argument is passed, that value will be returned instead of text.

Example where there in no localized value for txt parameter "Hello World":
>>> eggRMInstance.getText("MyProject", "catalog",
...                       "Hello World")
u'Hello World'
>>>
>>> eggRMInstance.getText("MyProject", "catalog",
...                             "Hello World",
...                             None)
None
>>>

If fallback was set to True in the EggTranslations.initialize method or the EggTranslations.setLocaleSet method, the EggTranslations.getText method will search all locales in the locale set till a gettext mo translation is found for the txt parameter.

If fallback was set to False in the EggTranslations.initialize method or the EggTranslations.setLocaleSet method, the EggTranslations.getText method will only search the current locale, which is the first locale in the locale set for a gettext mo translation for the txt parameter.

Note that the "all" default locale can not contain any key value pairs that point to gettext .mo files.

If a .mo gettext value is found in the "all" default locale, the .mo file will not be loaded by the EggTranslations.

Example:

A resource.ini file contains the following entry:
     [MyProject::fr]
     catalog = locale/fr/MyProject.mo
The locale/fr/myproject.mo file contains a localization of "Hello" to "Bonjour". Then, calling EggTranslations.getText looks this up in the .mo file:
   >>> egRMInstance.initialize("fr")
   >>> eggRMInstance.getText("MyProject", "catalog",
   ...                       "Hello")
   u'Bonjour'
Parameters:
  • project (ASCII str or unicode) - A project is a root namespace under which resources and localizations exist.

    A project name matches an egg name. An egg's info file can contain resource and localizations for more than one project.

    The project name must be either an ASCII str or unicode.
  • name (ASCII str or unicode) - name is the key to lookup in a resource ini file to retrieve the value specifed. For example, myname = this is my value.

    The name must be either an ASCII str or unicode.
  • txt (ASCII str or unicode) - The default text string which is used as look up key to retrieve a localized value from a gettext .mo file.

    The default text string is usual the English version of the text. The .mo gettext files will contain localizations of the English version with the English version as the key.
  • args (list) - An optional argument which if passed will be returned if no localzation found for txt. The type of the return value in the args list has no limitations.
Returns:
unicode localized text or either the original txt argument or the default value in args if no localization found.
Raises:
  • UnicodeDecodeError -

hasFallback(self)

source code 
Returns True if fallback was set to True in either the EggTranslations.initialize method or the EggTranslations.setLocaleSet method.
Returns:
boolean True if fallback set to True in initialize or setLocaleSet methods otherwise False.

hasTranslation(self, project, name, locale)

source code 
returns True if the gettext mo file for the given locale, project, and name is loaded.
Parameters:
  • project (ASCII str or unicode) - A project is a root namespace under which resources and localizations exist.

    A project name matches an egg name. An egg's info file can contain resource and localizations for more than one project.

    The project name must be either an ASCII str or unicode.
  • name (ASCII str or unicode) - name is the key to lookup in a resource ini file to retrieve the value specifed. For example, myname = this is my value.

    The name must be either an ASCII str or unicode.
  • locale (unicode or ASCII str) - The locale to scan for a gettext .mo translation. This parameter must contain a valid language / country locale i.e. "en_US" or "en".
Returns:
bool True if the .mo gettext file exists for the project, name, and locale otherwise False.

getAvailableLocales(self, project)

source code 
Returns a list of the locales that have registered one or more key value pairs for the given project.
Parameters:
  • project (ASCII str or unicode) - A project is a root namespace under which resources and localizations exist.

    A project name matches an egg name. An egg's info file can contain resource and localizations for more than one project.

    The project name must be either an ASCII str or unicode.
Returns:
list of str locale language / country codes.

getINIFileName(self)

source code 

Returns the unicode file name of the resource ini files. The default for the resource ini file is "resource.ini".

The name of the resource ini file is set in the EggTranslations.initialize method.
Returns:
unicode the name of the resource ini file.

getLocaleSet(self)

source code 
Returns a list of valid str locale language / country codes. The list is arranged in ascending fallback order.
Returns:
list of str locale language / country codes.

setLocaleSet(self, localeSet, fallback=True)

source code 

Resets the EggTranslations locale set list.

Resetting the locale set includes unloading all gettext .mo translations, loading the the gettext .mo translations for the current locale set, and setting the gettext locale fallback order if the fallback parameter is set to True.

Note the initial locale set for the EggTranslations must be set in the EggTranslations.initialize method.

Note, setting the EggTranslations locale set also adds the language code as a fallback for language / county code locale definitions when fallback is set to True. If the locale set contains 'fr_CA' this method will also add to the locale set 'fr' as a fallback for 'fr_CA'.
Parameters:
  • localeSet (ASCII str or unicode or list containing ASCII str or unicode values) - A unicode or str or list containing locale country and language codes. The value(s) must be able to be converted to ASCII.
  • fallback (boolean) - Indicates whether locale set fallback should take place. If set to True, the EggTranslations will search all locales in the locale set till a resource or gettext mo translation file is found. If set to False the EggTranslations will only try to locate a resource or gettext mo translation file for the current locale which is the first locale in the locale set.
Raises:
  • UnicodeEncodeError -
  • NameError -

normalizeLocale(self, locale)

source code 

Normalizes the str locale to lower case all lang codes and upper case all country codes.

Thus if passed "Fr_cA" this method would return "fr_CA".

If passed "FR" this method would return "fr"
Parameters:
  • locale (ASCII str) - a str locale
Returns:
str normalized version of the locale.

isValidLocaleForm(self, locale)

source code 

Returns True if the str locale passed has a valid form which is either lang code ("es") or lang code / country code ("es_UY").

This method does not validate whether the str matches a valid ISO code. Only that the form of the str is correct.
Parameters:
  • locale (ASCII str) - a str locale
Returns:
boolean True if locale has a valid form otherwise False

yieldFallbackLocales(self, localeSet)

source code 

Adds the lang code, if not already present, to the localeSet as a fallback to the lang country code.

Thus if passed ["fr_CA", "en_US", "es"] this method would return ["fr_CA", "fr", "en_US", "en", "es"]
Parameters:
  • localeSet (list) - a list containing ASCII str locales
Returns:
list containing original locale set str's and lang code fallbacks.

getDebugString(self)

source code 

Returns a str representation of the EggTranslations's egg loading values suitable for debugging using print, the logging package, or a UI dialog box.

The structure of the debug string is as follows:
EggTranslations
=========================
   INI FILE: ResourceFileName (Encoding)
   LOCALE SET: [localeSetValues]
   FALLBACK: True | False

   EggName
   ===============================

      ProjectName
      ---------------------
        [LocaleName]
           entryKey=entryValue
           gettextKey=getTextMoFile (LOADED | NOT_LOADED)


Here's an additional example output using real values::

EggTranslations
=========================
   INI FILE: 'resources.ini' (UTF-8)
   LOCALE SET: ['fr_CA', 'fr']
   FALLBACK: True

   MyProject 0.1
   ===============================

      myProject
      -------------------------
        [all]
           splashScreenImage = imgs/splash.png
           readme = README.txt

      myAlternateProject
      -------------------------
        [all]
           splashScreenImage = alternate/imgs/splash.png
           readme=alternate/README.txt

   MyProject.fr 0.1
   ===============================

      myProject
      ------------------------
        [fr_CA]
           splashScreenImage = locale/fr/imgs/splash.png
           readme = locale/fr/README.txt
           catalog= locale/fr/myProject.mo (LOADED)

      myAlternateProject
      ------------------------
        [fr_CA]
           splashScreenImage = alternate/locale/fr/imgs/splash.png
           readme = alternate/locale/fr/README.txt
           catalog = alternate/locale/fr/myProject.mo (LOADED)
Returns:
str debug string of EggTranslations current configuration in the UTF-8 encoding.

_parseINIFiles(self, dist)

source code 

Callback method passed to pkg_resources.add_activation_listener method.

For each egg distribution contained in the dist parameter:
  1. Parses the resource ini file (default name is "resource.ini") for each egg that contains one.
  2. Builds a cache of resources based on project, locale, and name.
  3. For each .mo value for a given project, locale, and name cache the file path to the .mo gettext file.
Parameters:
  • dist (pkg_resources.Distribution) - An egg package distribution
Raises: