translations_handler.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """
  2. Translation handler.
  3. """
  4. # Copyright (c) Jupyter Development Team.
  5. # Distributed under the terms of the Modified BSD License.
  6. from __future__ import annotations
  7. import json
  8. import traceback
  9. from functools import partial
  10. import tornado
  11. from .settings_utils import SchemaHandler
  12. from .translation_utils import (
  13. SYS_LOCALE,
  14. get_language_pack,
  15. get_language_packs,
  16. is_valid_locale,
  17. translator,
  18. )
  19. class TranslationsHandler(SchemaHandler):
  20. """An API handler for translations."""
  21. @tornado.web.authenticated
  22. async def get(self, locale: str | None = None) -> None:
  23. """
  24. Get installed language packs.
  25. If `locale` is equals to "default", the default locale will be used.
  26. Parameters
  27. ----------
  28. locale: str, optional
  29. If no locale is provided, it will list all the installed language packs.
  30. Default is `None`.
  31. """
  32. data: dict
  33. data, message = {}, ""
  34. try:
  35. current_loop = tornado.ioloop.IOLoop.current()
  36. if locale is None:
  37. data, message = await current_loop.run_in_executor(
  38. None,
  39. partial(get_language_packs, display_locale=self.get_current_locale()),
  40. )
  41. else:
  42. locale = locale or SYS_LOCALE
  43. if locale == "default":
  44. locale = SYS_LOCALE
  45. data, message = await current_loop.run_in_executor(
  46. None, partial(get_language_pack, locale)
  47. )
  48. if data == {} and not message:
  49. if is_valid_locale(locale):
  50. message = f"Language pack '{locale}' not installed!"
  51. else:
  52. message = f"Language pack '{locale}' not valid!"
  53. elif is_valid_locale(locale):
  54. # only change locale if the language pack is installed and valid
  55. translator.set_locale(locale)
  56. except Exception:
  57. message = traceback.format_exc()
  58. self.set_status(200)
  59. self.finish(json.dumps({"data": data, "message": message}))