NDOJ/judge/user_translations.py

44 lines
1.4 KiB
Python
Raw Normal View History

2020-01-21 06:35:58 +00:00
from django.conf import settings
from django.utils.safestring import SafeData, mark_safe
if settings.USE_I18N:
from django.utils.translation.trans_real import DjangoTranslation, get_language
_translations = {}
def translation(language):
global _translations
if language not in _translations:
2022-05-14 17:57:27 +00:00
_translations[language] = DjangoTranslation(language, domain="dmoj-user")
2020-01-21 06:35:58 +00:00
return _translations[language]
def do_translate(message, translation_function):
"""Copied from django.utils.translation.trans_real"""
# str() is allowing a bytestring message to remain bytestring on Python 2
2022-05-14 17:57:27 +00:00
eol_message = message.replace(str("\r\n"), str("\n")).replace(
str("\r"), str("\n")
)
2020-01-21 06:35:58 +00:00
if len(eol_message) == 0:
# Returns an empty value of the corresponding type if an empty message
# is given, instead of metadata, which is the default gettext behavior.
2022-05-14 17:57:27 +00:00
result = ""
2020-01-21 06:35:58 +00:00
else:
translation_object = translation(get_language())
result = getattr(translation_object, translation_function)(eol_message)
2022-11-01 01:43:06 +00:00
if not isinstance(result, str):
2022-05-14 17:57:27 +00:00
result = result.decode("utf-8")
2020-01-21 06:35:58 +00:00
if isinstance(message, SafeData):
return mark_safe(result)
return result
def gettext(message):
2022-05-14 17:57:27 +00:00
return do_translate(message, "gettext")
2020-01-21 06:35:58 +00:00
else:
2022-05-14 17:57:27 +00:00
2020-01-21 06:35:58 +00:00
def gettext(message):
return message