answerer.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import hashlib
  2. import random
  3. import string
  4. import uuid
  5. from flask_babel import gettext
  6. # required answerer attribute
  7. # specifies which search query keywords triggers this answerer
  8. keywords = ('random',)
  9. random_int_max = 2**31
  10. random_string_letters = string.ascii_lowercase + string.digits + string.ascii_uppercase
  11. def random_characters():
  12. return [random.choice(random_string_letters)
  13. for _ in range(random.randint(8, 32))]
  14. def random_string():
  15. return ''.join(random_characters())
  16. def random_float():
  17. return str(random.random())
  18. def random_int():
  19. return str(random.randint(-random_int_max, random_int_max))
  20. def random_sha256():
  21. m = hashlib.sha256()
  22. m.update(''.join(random_characters()).encode())
  23. return str(m.hexdigest())
  24. def random_uuid():
  25. return str(uuid.uuid4())
  26. random_types = {'string': random_string,
  27. 'int': random_int,
  28. 'float': random_float,
  29. 'sha256': random_sha256,
  30. 'uuid': random_uuid}
  31. # required answerer function
  32. # can return a list of results (any result type) for a given query
  33. def answer(query):
  34. parts = query.query.split()
  35. if len(parts) != 2:
  36. return []
  37. if parts[1] not in random_types:
  38. return []
  39. return [{'answer': random_types[parts[1]]()}]
  40. # required answerer function
  41. # returns information about the answerer
  42. def self_info():
  43. return {'name': gettext('Random value generator'),
  44. 'description': gettext('Generate different random values'),
  45. 'examples': ['random {}'.format(x) for x in random_types]}