redis_server.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Redis engine (offline)
  4. """
  5. import redis # pylint: disable=import-error
  6. engine_type = 'offline'
  7. # redis connection variables
  8. host = '127.0.0.1'
  9. port = 6379
  10. password = ''
  11. db = 0
  12. # engine specific variables
  13. paging = False
  14. result_template = 'key-value.html'
  15. exact_match_only = True
  16. _redis_client = None
  17. def init(_engine_settings):
  18. global _redis_client # pylint: disable=global-statement
  19. _redis_client = redis.StrictRedis(
  20. host = host,
  21. port = port,
  22. db = db,
  23. password = password or None,
  24. decode_responses = True,
  25. )
  26. def search(query, _params):
  27. global _redis_client # pylint: disable=global-statement
  28. if not exact_match_only:
  29. return search_keys(query)
  30. ret = _redis_client.hgetall(query)
  31. if ret:
  32. ret['template'] = result_template
  33. return [ret]
  34. if ' ' in query:
  35. qset, rest = query.split(' ', 1)
  36. ret = []
  37. for res in _redis_client.hscan_iter(
  38. qset, match='*{}*'.format(rest)
  39. ):
  40. ret.append({
  41. res[0]: res[1],
  42. 'template': result_template,
  43. })
  44. return ret
  45. return []
  46. def search_keys(query):
  47. global _redis_client # pylint: disable=global-statement
  48. ret = []
  49. for key in _redis_client.scan_iter(
  50. match='*{}*'.format(query)
  51. ):
  52. key_type = _redis_client.type(key)
  53. res = None
  54. if key_type == 'hash':
  55. res = _redis_client.hgetall(key)
  56. elif key_type == 'list':
  57. res = dict(enumerate(_redis_client.lrange(key, 0, -1)))
  58. if res:
  59. res['template'] = result_template
  60. res['redis_key'] = key
  61. ret.append(res)
  62. return ret