pythondjangohttp-accept-language

Python - Extract Main Language Code from HTTP / Browser


I need a way to determine the main language set in a browser. I found a really great solution for PHP but unfortunately I'm using Django / Python.

I think the information is within the HTTP_ACCEPT_LANGUAGE attribute of the HTTP Request.

Any ideas or ready-made functions for me?


Solution

  • You are looking for the request.META dictionary:

    print request.META['HTTP_ACCEPT_LANGUAGE']
    

    The WebOb project, a lightweight web framework, includes a handy accept parser that you could reuse in this case:

    from webob.acceptparse import Accept
    
    language_accept = Accept(request.META['HTTP_ACCEPT_LANGUAGE'])
    print language_accept.best_match(('en', 'de', 'fr'))
    print 'en' in language_accept
    

    Note that installing the WebOb package won't interfere with Django's functionality, we are just re-using a class from the package here that happens to be very useful.

    A short demo is always more illustrative:

    >>> header = 'en-us,en;q=0.5'
    >>> from webob.acceptparse import Accept
    >>> lang = Accept(header)
    >>> 'en' in lang
    True
    >>> 'fr' in lang
    False
    >>> lang.best_match(('en', 'de', 'fr'))
    'en'