aboutsummaryrefslogtreecommitdiff
blob: c98968da99c5af399eaa26752fe0ccef0256ec6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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