Overdue fix.
[wolnelektury.git] / src / experiments / base.py
1 import hashlib
2 from django.conf import settings
3
4
5 class Experiment:
6     slug = None
7     name = 'experiment'
8     explicit = False
9     size = 0
10
11     def qualify(self, request):
12         return True
13
14     def __init__(self, request):
15         self.value = self.get_value(request)
16
17     def override(self, value):
18         self.value = value
19         
20     def get_value(self, request):
21         overrides = getattr(settings, 'EXPERIMENTS_OVERRIDES', {})
22         slug = self.slug
23         if slug in overrides:
24             return overrides[slug]
25
26         if self.qualify(request) is False:
27             return None
28
29         cookie_value = request.COOKIES.get(f'EXPERIMENT_{slug}')
30         if cookie_value is not None:
31             if cookie_value == 'on':
32                 return True
33             elif cookie_value == 'off':
34                 return False
35
36         number = int(
37             hashlib.md5(
38                 (slug + request.META['REMOTE_ADDR']).encode('utf-8')
39             ).hexdigest(),
40             16
41         ) % 10e6 / 10e6
42         return number < self.size