answerer.py 1.7 KB

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