"""Parse the ``Accept-Language`` header."""
__docformat__ = "restructuredtext"
# Created: Thu Apr 28 02:52:11 PDT 2005
# Author: Shannon -jj Behrens
# Email: jjinux@users.sourceforge.net
#
# Copyright (c) Shannon -jj Behrens. All rights reserved.
import re
languageRegEx = re.compile(r"^[a-z]{2}(-[a-z]{2})?$", re.I)
def parseAcceptLanguage(header=None):
"""Parse the ``Accept-Language`` header.
Return a list of language tags sorted by their "q" values. For example,
"en-us,en;q=0.5" should return ``["en-us", "en"]``. If there is no
``Accept-Language`` header present, default to ``[]``.
"""
if header is None:
return []
langs = header.split(",")
qs = []
for lang in langs:
pieces = lang.split(";")
lang, params = pieces[0].strip().lower(), pieces[1:]
if not languageRegEx.match(lang):
continue
q = 1
for param in params:
lvalue, rvalue = param.split("=")
lvalue = lvalue.strip().lower()
rvalue = rvalue.strip()
if lvalue == "q":
q = float(rvalue)
qs.append((lang, q))
qs.sort(lambda a, b: -cmp(a[1], b[1]))
return [lang for (lang, q) in qs]
|