answerer.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. def random_color():
  26. color = "%06x" % random.randint(0, 0xFFFFFF)
  27. return f"#{color.upper()}"
  28. random_types = {
  29. 'string': random_string,
  30. 'int': random_int,
  31. 'float': random_float,
  32. 'sha256': random_sha256,
  33. 'uuid': random_uuid,
  34. 'color': random_color,
  35. }
  36. # required answerer function
  37. # can return a list of results (any result type) for a given query
  38. def answer(query):
  39. parts = query.query.split()
  40. if len(parts) != 2:
  41. return []
  42. if parts[1] not in random_types:
  43. return []
  44. return [{'answer': random_types[parts[1]]()}]
  45. # required answerer function
  46. # returns information about the answerer
  47. def self_info():
  48. return {
  49. 'name': gettext('Random value generator'),
  50. 'description': gettext('Generate different random values'),
  51. 'examples': ['random {}'.format(x) for x in random_types],
  52. }