Merge pull request #304 from talyian/master

Improve Accept-Language header ordering
pull/326/head
Igor Chubin 5 years ago committed by GitHub
commit 5ae8fd90a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -78,23 +78,31 @@ def get_answer_language(request):
try: try:
if language.split(";")[0] == language: if language.split(";")[0] == language:
# no q => q = 1 # no q => q = 1
locale_q_pairs.append((language.strip(), "1")) locale_q_pairs.append((language.strip(), 1))
else: else:
locale = language.split(";")[0].strip() locale = language.split(";")[0].strip()
weight = language.split(";")[1].split("=")[1] weight = float(language.split(";")[1].split("=")[1])
locale_q_pairs.append((locale, weight)) locale_q_pairs.append((locale, weight))
except IndexError: except (IndexError, ValueError):
pass pass
return locale_q_pairs return locale_q_pairs
def _find_supported_language(accepted_languages): def _find_supported_language(accepted_languages):
def supported_langs():
"""Yields all pairs in the Accept-Language header
supported in SUPPORTED_LANGS or None if 'en' is the preferred"""
for lang_tuple in accepted_languages: for lang_tuple in accepted_languages:
lang = lang_tuple[0] lang = lang_tuple[0]
if '-' in lang: if '-' in lang:
lang = lang.split('-', 1)[0] lang = lang.split('-', 1)[0]
if lang in SUPPORTED_LANGS: if lang in SUPPORTED_LANGS:
return lang yield lang, lang_tuple[1]
elif lang == 'en':
yield None, lang_tuple[1]
try:
return max(supported_langs(), key=lambda lang_tuple:lang_tuple[1])[0]
except ValueError:
return None return None
lang = None lang = None

Loading…
Cancel
Save