answerer.py 1.4 KB

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