Frage

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?

War es hilfreich?

Lösung

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'

Andere Tipps

This is a function that i used and that is my creation self.

def language(self):
        if 'HTTP_ACCEPT_LANGUAGE' in self._request.META:
            lang = self._request.META['HTTP_ACCEPT_LANGUAGE']
            return str(lang[:2])
        else:
            return 'en'

Just call it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top