3

我需要一种方法来确定浏览器中设置的主要语言。我为 PHP 找到了一个非常好的解决方案,但不幸的是我使用的是 Django/Python。

我认为该信息在 HTTP 请求的 HTTP_ACCEPT_LANGUAGE 属性中。

对我有什么想法或现成的功能吗?

4

2 回答 2

1

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'
于 2012-09-04T19:18:18.553 回答
0

这是我使用的一个功能,那是我的创作自我。

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'

就叫吧。

于 2015-11-17T18:15:13.357 回答