i18n.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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): # pragma: no cover
  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. return getter(languages)
  30. class DefaultTranslations:
  31. """
  32. A WTForms translations object to wrap translations objects which use
  33. ugettext/ungettext.
  34. """
  35. def __init__(self, translations):
  36. self.translations = translations
  37. def gettext(self, string):
  38. return self.translations.ugettext(string)
  39. def ngettext(self, singular, plural, n):
  40. return self.translations.ungettext(singular, plural, n)
  41. class DummyTranslations:
  42. """
  43. A translations object which simply returns unmodified strings.
  44. This is typically used when translations are disabled or if no valid
  45. translations provider can be found.
  46. """
  47. def gettext(self, string):
  48. return string
  49. def ngettext(self, singular, plural, n):
  50. if n == 1:
  51. return singular
  52. return plural