context_processors.py 1.22 KB
Newer Older
1
from random import sample
2
3
4
5
6

from partners.models import Partner


def showcased_partners(request):
7
8
9
10
11
    """
    Generate a sequence of showcased partners (banners)

    For each user we generate a sequence of banners. This sequence
    is then stored for that user, because doing it randomly creates
12
    a feel of an artificial 'bias' towards certain partners. Doing
13
14
15
    it this way ensures that everyone gets an exactly fair number of
    views.
    """
16
17
18
19
20
21
22
    all_partners = Partner.objects.filter(is_active=True).order_by('id')
    ids = [partner.id for partner in all_partners]

    # check if partners have changed; if so, update sequence in session
    if ('partner_sequence' not in request.session or
            'partner_ids' not in request.session or
            request.session['partner_ids'] != ids):
23
        # Store a list of partner ids to allow checking for changes in partners
24
25
        request.session['partner_ids'] = ids
        request.session['partner_sequence'] = sample(ids, len(ids))
26
27
28
29
30

    sequence = request.session['partner_sequence']
    chosen, rest = sequence[:2], sequence[2:]
    request.session['partner_sequence'] = rest + chosen

31
32
33
    return {
        'showcased_partners': [p for p in all_partners if p.id in chosen],
    }