summaryrefslogtreecommitdiff
path: root/searx/answerers/random/answerer.py
blob: 2dfb08804f4c0d6333472d178f85067b2feaf5a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import hashlib
import random
import string
import sys
import uuid
from flask_babel import gettext

# required answerer attribute
# specifies which search query keywords triggers this answerer
keywords = ('random',)

random_int_max = 2**31

if sys.version_info[0] == 2:
    random_string_letters = string.lowercase + string.digits + string.uppercase
else:
    unicode = str
    random_string_letters = string.ascii_lowercase + string.digits + string.ascii_uppercase


def random_characters():
    return [random.choice(random_string_letters)
            for _ in range(random.randint(8, 32))]


def random_string():
    return u''.join(random_characters())


def random_float():
    return unicode(random.random())


def random_int():
    return unicode(random.randint(-random_int_max, random_int_max))


def random_sha256():
    m = hashlib.sha256()
    m.update(b''.join(random_characters()))
    return unicode(m.hexdigest())


def random_uuid():
    return unicode(uuid.uuid4())


random_types = {b'string': random_string,
                b'int': random_int,
                b'float': random_float,
                b'sha256': random_sha256,
                b'uuid': random_uuid}


# required answerer function
# can return a list of results (any result type) for a given query
def answer(query):
    parts = query.query.split()
    if len(parts) != 2:
        return []

    if parts[1] not in random_types:
        return []

    return [{'answer': random_types[parts[1]]()}]


# required answerer function
# returns information about the answerer
def self_info():
    return {'name': gettext('Random value generator'),
            'description': gettext('Generate different random values'),
            'examples': [u'random {}'.format(x.decode('utf-8')) for x in random_types]}