i18n.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import os
  2. def messages_path():
  3. """
  4. Determine the path to the 'messages' directory as best possible.
  5. """
  6. module_path = os.path.abspath(__file__)
  7. locale_path = os.path.join(os.path.dirname(module_path), 'locale')
  8. if not os.path.exists(locale_path):
  9. locale_path = '/usr/share/locale'
  10. return locale_path
  11. def get_builtin_gnu_translations(languages=None):
  12. """
  13. Get a gettext.GNUTranslations object pointing at the
  14. included translation files.
  15. :param languages:
  16. A list of languages to try, in order. If omitted or None, then
  17. gettext will try to use locale information from the environment.
  18. """
  19. import gettext
  20. return gettext.translation('wtforms', messages_path(), languages)
  21. def get_translations(languages=None, getter=get_builtin_gnu_translations):
  22. """
  23. Get a WTForms translation object which wraps a low-level translations object.
  24. :param languages:
  25. A sequence of languages to try, in order.
  26. :param getter:
  27. A single-argument callable which returns a low-level translations object.
  28. """
  29. translations = getter(languages)
  30. if hasattr(translations, 'ugettext'):
  31. return DefaultTranslations(translations)
  32. else:
  33. # Python 3 has no ugettext/ungettext, so just return the translations object.
  34. return translations
  35. class DefaultTranslations(object):
  36. """
  37. A WTForms translations object to wrap translations objects which use
  38. ugettext/ungettext.
  39. """
  40. def __init__(self, translations):
  41. self.translations = translations
  42. def gettext(self, string):
  43. return self.translations.ugettext(string)
  44. def ngettext(self, singular, plural, n):
  45. return self.translations.ungettext(singular, plural, n)
  46. class DummyTranslations(object):
  47. """
  48. A translations object which simply returns unmodified strings.
  49. This is typically used when translations are disabled or if no valid
  50. translations provider can be found.
  51. """
  52. def gettext(self, string):
  53. return string
  54. def ngettext(self, singular, plural, n):
  55. if n == 1:
  56. return singular
  57. return plural