Flask-Babel zh-TW, zh-HK 對應到 zh_Hant , zh-CN 、 zh-SG 對應到 zh_Hans
Flask-Babel 下, zh-TW, zh-HK 語言對應到 zh_Hant , zh-CN 、 zh-SG 語言對應到 zh_Hans 的解法。
Fixing request.accept_languages.best_match() to match zh-TW, zh-HK against zh_Hant, and zh-CN, zh-SG to zh_Hans in Flask-Babel.
from babel import Locale
from werkzeug.datastructures import LanguageAccept
@babel.localeselector
def get_locale():
"""Returns the locale of the user
:return: The locale of the user.
"""
return __fix_accept_language(request.accept_languages)
.best_match(current_app.config["ALL_LOCALES"])
def __fix_accept_language(accept: LanguageAccept) -> LanguageAccept:
"""Fixes the accept language so that territory variants may be matched to
script variants. For example, zh_TW, zh_HK to zh_Hant, and zh_CN, zh_SG to
zh_Hans. This is to solve the issue that Flask only recognizes the script
variants, like zh_Hant and zh_Hans.
:param accept: The original HTTP accept languages.
:return: The fixed HTTP accept languages.
"""
accept_list: t.List[t.Tuple[str, float]] = list(accept)
to_add: t.List[t.Tuple[str, float]] = []
for pair in accept_list:
locale: Locale = Locale.parse(pair[0].replace("-", "_"))
if locale.script is not None:
tag: str = F"{locale.language}-{locale.script}"
if tag not in accept:
to_add.append((tag, pair[1]))
accept_list.extend(to_add)
return LanguageAccept(accept_list)