aboutsummaryrefslogtreecommitdiffstats
path: root/fatcat_scholar/hacks.py
diff options
context:
space:
mode:
authorBryan Newbold <bnewbold@archive.org>2020-10-22 19:01:13 -0700
committerBryan Newbold <bnewbold@archive.org>2020-10-22 19:01:13 -0700
commit08156558afdd37fdf2bb62a97e1814aab1f21945 (patch)
tree25d9a8f878f856f2732b5728eb654345b66ad752 /fatcat_scholar/hacks.py
parentea28911d14f3996ace13bf95ce1b8f6537d43fcc (diff)
downloadfatcat-scholar-08156558afdd37fdf2bb62a97e1814aab1f21945.tar.gz
fatcat-scholar-08156558afdd37fdf2bb62a97e1814aab1f21945.zip
web: basic Accept-Language HTTP negotiation
Diffstat (limited to 'fatcat_scholar/hacks.py')
-rw-r--r--fatcat_scholar/hacks.py26
1 files changed, 26 insertions, 0 deletions
diff --git a/fatcat_scholar/hacks.py b/fatcat_scholar/hacks.py
index 710a25f..fc16564 100644
--- a/fatcat_scholar/hacks.py
+++ b/fatcat_scholar/hacks.py
@@ -51,3 +51,29 @@ class Jinja2Templates:
media_type=media_type,
background=background,
)
+
+
+def parse_accept_lang(header: str, options: typing.List[str]) -> typing.Optional[str]:
+ """
+ Crude HTTP Accept-Language content negotiation.
+ Assumes that languages are specified in order of priority, etc.
+ """
+ if not header:
+ return None
+ chunks = [v.split(";")[0].split("-")[0] for v in header.split(",")]
+ for c in chunks:
+ if len(c) == 2 and c in options:
+ return c
+ return None
+
+
+def test_parse_accept_lang() -> None:
+ assert parse_accept_lang("", []) == None
+ assert parse_accept_lang("en,de", []) == None
+ assert parse_accept_lang("en,de", ["en"]) == "en"
+ assert parse_accept_lang("en-GB,de", ["en"]) == "en"
+ assert parse_accept_lang("en,de", ["de"]) == "de"
+ assert (
+ parse_accept_lang("en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2", ["de"])
+ == "de"
+ )