aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--gentoo_ads/ads/views.py37
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