[Python] Parse Accept-Language in HTTP Request Header


The Accept-Language field in HTTP Request header is important for determining user locale. In this post, we will show how to parse Accept-Language field using Python. The following parseAcceptLanguage function takes Accept-Language field as argument, and returns a Python list which contains pairs of (locale, q). The order of (locale, q) pairs are determined by locale preference of the user (highest preference first).

Python Parse Accept-Language

def parseAcceptLanguage(acceptLanguage):
  languages = acceptLanguage.split(",")
  locale_q_pairs = []

  for language in languages:
    if language.split(";")[0] == language:
      # no q => q = 1
      locale_q_pairs.append((language.strip(), "1"))
    else:
      locale = language.split(";")[0].strip()
      q = language.split(";")[1].split("=")[1]
      locale_q_pairs.append((locale, q))

  return locale_q_pairs

Example Usage and Output

>>> print(parseAcceptLanguage('da, en-gb;q=0.8, en;q=0.7'))
[('da', '1'), ('en-gb', '0.8'), ('en', '0.7')]

>>> print(parseAcceptLanguage('zh, en-us; q=0.8, en; q=0.6'))
[('zh', '1'), ('en-us', '0.8'), ('en', '0.6')]

>>> print(parseAcceptLanguage('es-mx, es, en'))
[('es-mx', '1'), ('es', '1'), ('en', '1')]

>>> print(parseAcceptLanguage('de; q=1.0, en; q=0.5'))
[('de', '1.0'), ('en', '0.5')]

To know how to detect user locale/language according to Accept-Language field in HTTP request header, please refer to the post "Detect User Language (Locale) on Google App Engine Python" [4].


References:

[1]List of HTTP header fields
[2]HTTP/1.1: Header Field Definitions
[3]Accept-Language used for locale setting
[4]Detect User Language (Locale) on Google App Engine Python