form.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import warnings
  2. from wtforms import form
  3. from wtforms.ext.i18n.utils import get_translations
  4. translations_cache = {}
  5. class Form(form.Form):
  6. """
  7. Base form for a simple localized WTForms form.
  8. **NOTE** this class is now un-necessary as the i18n features have
  9. been moved into the core of WTForms, and will be removed in WTForms 3.0.
  10. This will use the stdlib gettext library to retrieve an appropriate
  11. translations object for the language, by default using the locale
  12. information from the environment.
  13. If the LANGUAGES class variable is overridden and set to a sequence of
  14. strings, this will be a list of languages by priority to use instead, e.g::
  15. LANGUAGES = ['en_GB', 'en']
  16. One can also provide the languages by passing `LANGUAGES=` to the
  17. constructor of the form.
  18. Translations objects are cached to prevent having to get a new one for the
  19. same languages every instantiation.
  20. """
  21. LANGUAGES = None
  22. def __init__(self, *args, **kwargs):
  23. warnings.warn(
  24. 'i18n is now in core, wtforms.ext.i18n will be removed in WTForms 3.0',
  25. DeprecationWarning, stacklevel=2
  26. )
  27. if 'LANGUAGES' in kwargs:
  28. self.LANGUAGES = kwargs.pop('LANGUAGES')
  29. super(Form, self).__init__(*args, **kwargs)
  30. def _get_translations(self):
  31. languages = tuple(self.LANGUAGES) if self.LANGUAGES else (self.meta.locales or None)
  32. if languages not in translations_cache:
  33. translations_cache[languages] = get_translations(languages)
  34. return translations_cache[languages]