Proper way to get the browser's preferred language in WebOb?

48 views
Skip to first unread message

Christopher Webber

unread,
Nov 8, 2011, 11:38:21 AM11/8/11
to Paste Users
In a couple of the codebases I run, we used to have code along these
lines to discover the browser's preferred language:

accept_lang_matches = request.accept_language.best_matches()
if accept_lang_matches:
locale = accept_lang_matches[0]
else:
locale = 'en'

In a recent release of WebOb, accept_language.best_matches() was
removed, so this code broke.

In the WebOb release notes, I saw:

Accept.best_matches() is gone; use list(request.accept) or
request.accept.best_match(..) instead (applies to all Accept-*
headers) or similar with request.accept_language.

I took this to mean that we should do:

locale = request.accept_language.best_match(
request.accept_language, 'en')

... there was a bug preventing that, so I submitted a patch for it,
which did get merged:

https://github.com/Pylons/webob/issues/5

but in the meanwhile I apparently wasn't doing the right thing (even
if
my fix was right ;))? What's the proper way to select the browser's
preferred locale, defaulting back to English?

Thanks!
- Christopher Allan Webber

Sergey Schetinin

unread,
Nov 8, 2011, 12:09:15 PM11/8/11
to Christopher Webber, Paste Users
There are two general usage scenarios for accept headers -- one is when you have a specific set of supported languages (or content-types, charsets, encodings, depending on the header) and want to find out which one is preferred by the user-agent. For this you use .best_match(offers).

Another scenario is when you don't have a complete list of supported languages and want to check them one by one, in that case you iterate over the header: for lang in req.accept_languages. That iterates over the supported languages in the order from the most preferred to the least.

Using the best_match and passing the header wrapper itself as a set the offers list is really weird but maybe does return the correct result.

If you really don't want to use either of the previous scenarios and just get the most preferred language or 'en', do this:

def get_lang(langs):
    if not langs:
        return 'en'
    return iter(langs).next() 
    # or return list(langs)[0] if you prefer

get_lang(req.accept_languages)


My guess however, is that you will probably be better off using one of the scenarios above.




--
You received this message because you are subscribed to the Google Groups "Paste Users" group.
To post to this group, send email to paste...@googlegroups.com.
To unsubscribe from this group, send email to paste-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/paste-users?hl=en.




--
http://self.maluke.com/

Christopher Allan Webber

unread,
Nov 8, 2011, 4:37:10 PM11/8/11
to Sergey Schetinin, Paste Users
Thanks for this information! I'll take it into account.
Reply all
Reply to author
Forward
0 new messages