Skip to content

Commit

Permalink
Enhance parsing of Accept-Language quality values
Browse files Browse the repository at this point in the history
The following cases were not possible:
"Accept-Language: en-US; foo=bar; q=0.9"
"Accept-Language: en-US; q = 0.9"
  • Loading branch information
spaceone committed Aug 29, 2022
1 parent 7689e3f commit e336fdd
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
8 changes: 8 additions & 0 deletions tornado/test/web_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3183,6 +3183,14 @@ def test_accept_language(self):
response = self.fetch("/", headers={"Accept-Language": "fr-FR; q=0.9"})
self.assertEqual(response.headers["Content-Language"], "fr-FR")

response = self.fetch("/", headers={"Accept-Language": "fr-FR; foo=bar; q=0.9"})
self.assertEqual(response.headers["Content-Language"], "fr-FR")

response = self.fetch(
"/", headers={"Accept-Language": "fr-FR; foo=bar; q = 0.9"}
)
self.assertEqual(response.headers["Content-Language"], "fr-FR")

def test_accept_language_ignore(self):
response = self.fetch("/", headers={"Accept-Language": "fr-FR;q=0"})
self.assertEqual(response.headers["Content-Language"], "en-US")
Expand Down
14 changes: 9 additions & 5 deletions tornado/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -1292,17 +1292,21 @@ def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale:
locales = []
for language in languages:
parts = language.strip().split(";")
if len(parts) > 1 and parts[1].strip().startswith("q="):
score = 1.0
for part in (
x.split("=", 1)[1].strip()
for x in parts[1:]
if "=" in x and x.split("=", 1)[0].strip() == "q"
):
try:
score = float(parts[1].strip()[2:])
score = float(part)
if score < 0:
raise ValueError()
except (ValueError, TypeError):
score = 0.0
else:
score = 1.0
break
if score > 0:
locales.append((parts[0], score))
locales.append((parts[0].strip(), score))
if locales:
locales.sort(key=lambda pair: pair[1], reverse=True)
codes = [loc[0] for loc in locales]
Expand Down

0 comments on commit e336fdd

Please sign in to comment.