Fixed #28642 -- Added caching to parse_accept_lang_header().

This commit is contained in:
Tom 2017-09-19 23:16:48 +01:00 committed by Tim Graham
parent f04e6732c3
commit f1c007bbf2
2 changed files with 7 additions and 6 deletions

View File

@ -509,25 +509,26 @@ def get_language_from_request(request, check_path=False):
return settings.LANGUAGE_CODE return settings.LANGUAGE_CODE
@functools.lru_cache(maxsize=1000)
def parse_accept_lang_header(lang_string): def parse_accept_lang_header(lang_string):
""" """
Parse the lang_string, which is the body of an HTTP Accept-Language Parse the lang_string, which is the body of an HTTP Accept-Language
header, and return a list of (lang, q-value), ordered by 'q' values. header, and return a tuple of (lang, q-value), ordered by 'q' values.
Return an empty list if there are any format errors in lang_string. Return an empty tuple if there are any format errors in lang_string.
""" """
result = [] result = []
pieces = accept_language_re.split(lang_string.lower()) pieces = accept_language_re.split(lang_string.lower())
if pieces[-1]: if pieces[-1]:
return [] return tuple()
for i in range(0, len(pieces) - 1, 3): for i in range(0, len(pieces) - 1, 3):
first, lang, priority = pieces[i:i + 3] first, lang, priority = pieces[i:i + 3]
if first: if first:
return [] return tuple()
if priority: if priority:
priority = float(priority) priority = float(priority)
else: else:
priority = 1.0 priority = 1.0
result.append((lang, priority)) result.append((lang, priority))
result.sort(key=lambda k: k[1], reverse=True) result.sort(key=lambda k: k[1], reverse=True)
return result return tuple(result)

View File

@ -1133,7 +1133,7 @@ class MiscTests(SimpleTestCase):
] ]
for value, expected in tests: for value, expected in tests:
with self.subTest(value=value): with self.subTest(value=value):
self.assertEqual(trans_real.parse_accept_lang_header(value), expected) self.assertEqual(trans_real.parse_accept_lang_header(value), tuple(expected))
def test_parse_literal_http_header(self): def test_parse_literal_http_header(self):
""" """