answerer.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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) for _ in range(random.randint(8, 32))]
  13. def random_string():
  14. return ''.join(random_characters())
  15. def random_float():
  16. return str(random.random())
  17. def random_int():
  18. return str(random.randint(-random_int_max, random_int_max))
  19. def random_sha256():
  20. m = hashlib.sha256()
  21. m.update(''.join(random_characters()).encode())
  22. return str(m.hexdigest())
  23. def random_uuid():
  24. return str(uuid.uuid4())
  25. random_types = {
  26. 'string': random_string,
  27. 'int': random_int,
  28. 'float': random_float,
  29. 'sha256': random_sha256,
  30. 'uuid': random_uuid,
  31. }
  32. # required answerer function
  33. # can return a list of results (any result type) for a given query
  34. def answer(query):
  35. parts = query.query.split()
  36. if len(parts) != 2:
  37. return []
  38. if parts[1] not in random_types:
  39. return []
  40. return [{'answer': random_types[parts[1]]()}]
  41. # required answerer function
  42. # returns information about the answerer
  43. def self_info():
  44. return {
  45. 'name': gettext('Random value generator'),
  46. 'description': gettext('Generate different random values'),
  47. 'examples': ['random {}'.format(x) for x in random_types],
  48. }