Upgrades.
[wolnelektury.git] / src / experiments / middleware.py
1 import hashlib
2 from django.conf import settings
3
4
5 def experiments_middleware(get_response):
6     def middleware(request):
7         exps = {}
8
9         overrides = getattr(settings, 'EXPERIMENTS_OVERRIDES', {})
10         for exp in settings.EXPERIMENTS:
11             slug = exp['slug']
12             if slug in overrides:
13                 exps[slug] = overrides[slug]
14                 continue
15
16             cookie_value = request.COOKIES.get(f'EXPERIMENT_{slug}')
17             if cookie_value is not None:
18                 for cohort in exp.get('cohorts', []):
19                     if cohort['value'] == cookie_value:
20                         exps[slug] = cookie_value
21                         break
22
23             if slug not in exps:
24                 number = int(
25                     # TODO sth else?
26                     hashlib.md5(
27                         (slug + request.META['REMOTE_ADDR']).encode('utf-8')
28                     ).hexdigest(),
29                     16
30                 ) % 10e6 / 10e6
31                 for cohort in exp.get('cohorts', []):
32                     number -= cohort.get('size', 1)
33                     if number < 0:
34                         exps[slug] = cohort['value']
35                         break
36
37         request.EXPERIMENTS = exps
38         response = get_response(request)
39         return response
40
41     return middleware