Tag description update API
[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.manual = self.get_value(request)
16
17     def override(self, value):
18         self.value = value
19         self.manual = False
20         
21     def get_value(self, request):
22         overrides = getattr(settings, 'EXPERIMENTS_OVERRIDES', {})
23         slug = self.slug
24         if slug in overrides:
25             return overrides[slug], False
26
27         if self.qualify(request) is False:
28             return None, False
29
30         cookie_value = request.COOKIES.get(f'EXPERIMENT_{slug}')
31         if cookie_value is not None:
32             if cookie_value == 'on':
33                 return True, True
34             elif cookie_value == 'off':
35                 return False, True
36
37         number = int(
38             hashlib.md5(
39                 (slug + request.META['REMOTE_ADDR']).encode('utf-8')
40             ).hexdigest(),
41             16
42         ) % 10e6 / 10e6
43         return number < self.size, False