diff options
author | Robin H. Johnson <robbat2@gentoo.org> | 2010-12-14 21:19:55 +0000 |
---|---|---|
committer | Robin H. Johnson <robbat2@gentoo.org> | 2010-12-14 21:19:55 +0000 |
commit | eccc89c4e7e3ff69fb23528cb718789e48879a23 (patch) | |
tree | 9a678f660cb8e6cab972dbff741fd1a83a289859 | |
parent | Merge branch 'master' of git+ssh://git.overlays.gentoo.org/proj/gentoo-ads (diff) | |
download | gentoo-ads-eccc89c4e7e3ff69fb23528cb718789e48879a23.tar.gz gentoo-ads-eccc89c4e7e3ff69fb23528cb718789e48879a23.tar.bz2 gentoo-ads-eccc89c4e7e3ff69fb23528cb718789e48879a23.zip |
Implement better language handling.
-rw-r--r-- | gentoo_ads/ads/views.py | 37 |
1 files changed, 25 insertions, 12 deletions
diff --git a/gentoo_ads/ads/views.py b/gentoo_ads/ads/views.py index 1fb1bcd..85e19f0 100644 --- a/gentoo_ads/ads/views.py +++ b/gentoo_ads/ads/views.py @@ -5,27 +5,40 @@ from django.shortcuts import render_to_response from django.conf import settings from random import randint import logging +import re + +META_LANG_KEY = 'HTTP_ACCEPT_LANGUAGE' def serve_ads(request): sample = _weighted_random_sample(settings.ADS_STRUCT) - ads = [_trans_ad(a, request.META['HTTP_ACCEPT_LANGUAGE'].split(',')[0]) for a in sample] + accept_langs = _build_lang_array(request) + ads = [_trans_ad(a, accept_langs) for a in sample] return render_to_response('ads.html', {'ads': ads, 'MEDIA_URL': settings.MEDIA_URL,}) -def _trans_ad(ad, lang): - +def _build_lang_array(request): + accept_langs = [settings.DEFAULT_ADS_LANG] + if META_LANG_KEY in request.META: + # Ignore priority for now, hopefully they are in the correct order + # TODO: reorder per HTTP language RFC + accept_langs = [re.sub(';q=[0-9.]+', '' ,_).strip() for _ in request.META[META_LANG_KEY].split(',')] + # Handle dialects + for _ in accept_langs: + if '-' in _: + accept_langs += [ re.sub('[-_][_-a-zA-Z0-9]+', '', _) ] + return accept_langs + +def _match_langs(accept_langs, available_langs): + common_langs = set(accept_langs) & set(available_langs) + for _ in accept_langs: + return _ if _ in common_langs + +def _trans_ad(ad, accept_langs): for k in settings.TRANS_KEYS: if k not in ad: continue if isinstance(ad[k], dict): - if lang in ad[k]: - ad[k] = ad[k][lang] - - elif lang.split('-')[0] in ad[k]: - s = lang.split('-')[0] - ad[k] = ad[k][s] - - else: - ad[k] = ad[k][settings.DEFAULT_ADS_LANG] + lang = _match_langs(accept_langs, ad[k].keys()) + ad[k] = ad[k][lang] return ad |