mise-en-production
[auf_framonde.git] / project / cmsplugin_contact_plus / simplemathcaptcha / utils.py
1 from __future__ import absolute_import
2 from __future__ import unicode_literals
3
4 from random import randint, choice
5 from hashlib import sha1
6
7 from django.conf import settings
8 from django.utils import six
9
10 MULTIPLY = '*'
11 ADD = '+'
12 SUBTRACT = '-'
13 CALCULATIONS = {
14 MULTIPLY: lambda a, b: a * b,
15 ADD: lambda a, b: a + b,
16 SUBTRACT: lambda a, b: a - b,
17 }
18 OPERATORS = tuple(CALCULATIONS)
19
20
21 def hash_answer(value):
22 answer = six.text_type(value)
23 to_encode = (settings.SECRET_KEY + answer).encode('utf-8')
24 return sha1(to_encode).hexdigest()
25
26
27 def get_operator():
28 return choice(OPERATORS)
29
30
31 def get_numbers(start_int, end_int, operator):
32 x = randint(start_int, end_int)
33 y = randint(start_int, end_int)
34
35 #avoid negative results for subtraction
36 if y > x and operator == SUBTRACT:
37 x, y = y, x
38
39 return x, y
40
41
42 def calculate(x, y, operator):
43 func = CALCULATIONS[operator]
44 total = func(x, y)
45 return total