aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'gentoo_ads/ads/views.py')
-rw-r--r--gentoo_ads/ads/views.py30
1 files changed, 30 insertions, 0 deletions
diff --git a/gentoo_ads/ads/views.py b/gentoo_ads/ads/views.py
new file mode 100644
index 0000000..c98968d
--- /dev/null
+++ b/gentoo_ads/ads/views.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+# Create your views here.
+
+from django.shortcuts import render_to_response
+from django.conf import settings
+from random import randint
+
+def serve_ads(request):
+ sample = _weighted_random_sample(settings.ADS_STRUCT)
+ return render_to_response('ads.html', {'ads': sample, 'MEDIA_URL': settings.MEDIA_URL,})
+
+def _weighted_random_sample(ads):
+ ads_out = []
+
+ for i in xrange(settings.ADS_LENGTH):
+ indices = [a['weight'] for a in ads]
+ s = sum(indices)
+ r = randint(0, s-1)
+ cur_total = 0
+
+ for ad_i in xrange(len(ads)):
+ ad = ads[ad_i]
+ cur_total += ad['weight']
+
+ if r < cur_total:
+ ads_out.append(ad)
+ ads = ads[:ad_i] + ads[ad_i + 1:]
+ break
+
+ return ads_out \ No newline at end of file