Skip to content

Instantly share code, notes, and snippets.

@evilaliv3
Last active August 29, 2015 14:15
Show Gist options
  • Save evilaliv3/5a9cd11eaa0cf60da425 to your computer and use it in GitHub Desktop.
Save evilaliv3/5a9cd11eaa0cf60da425 to your computer and use it in GitHub Desktop.
def getBestLangMatch(accept_language, supported_lcs):
def parse_accept_language(accept_language):
return [l.split(';')[0] for l in accept_language.replace(" ", "").split(',')]
def language_only(lc):
if '-' in lc:
lc = lc.split('-')[0]
return lc
for lc in parse_accept_language(accept_language):
# returns es-PT if es-PT is available (perfect match)
for l in supported_lcs:
if lc.lower() == l.lower():
return l
lc = language_only(lc)
# returns es if asking for es-PT with
# es-PT not available but es available
for l in supported_lcs:
if lc.lower() == l.lower():
return l
# returns es-ES if asking for es-PT with
# es-PT and es not available but es-ES available
for l in supported_lcs:
if lc.lower() == language_only(l).lower():
return l
return 'en-US' # last resort
# Should return ar
print getBestLangMatch('uk, ar;q=0.8, ur;q=0.7', supported_lc)
# Should return es-ES
print getBestLangMatch('uk, ur;q = 0.8, es; q=0 . 7', supported_lc)
# Should return es-ES
print getBestLangMatch('uk,ur;q=0.8,es-Pt;q=0.7', supported_lc)
# Should return es-ES
print getBestLangMatch('uk,ur;q=0.8,es-eS;q=0.7', supported_lc)
# Should return en-US
print getBestLangMatch('xx,yy;q=0.8,zz;q=0.7', supported_lc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment