redis_server.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Redis is an open source (BSD licensed), in-memory data structure (key value
  3. based) store. Before configuring the ``redis_server`` engine, you must install
  4. the dependency redis_.
  5. Configuration
  6. =============
  7. Select a database to search in and set its index in the option ``db``. You can
  8. either look for exact matches or use partial keywords to find what you are
  9. looking for by configuring ``exact_match_only``.
  10. Example
  11. =======
  12. Below is an example configuration:
  13. .. code:: yaml
  14. # Required dependency: redis
  15. - name: myredis
  16. shortcut : rds
  17. engine: redis_server
  18. exact_match_only: false
  19. host: '127.0.0.1'
  20. port: 6379
  21. enable_http: true
  22. password: ''
  23. db: 0
  24. Implementations
  25. ===============
  26. """
  27. import redis # pylint: disable=import-error
  28. engine_type = 'offline'
  29. # redis connection variables
  30. host = '127.0.0.1'
  31. port = 6379
  32. password = ''
  33. db = 0
  34. # engine specific variables
  35. paging = False
  36. result_template = 'key-value.html'
  37. exact_match_only = True
  38. _redis_client = None
  39. def init(_engine_settings):
  40. global _redis_client # pylint: disable=global-statement
  41. _redis_client = redis.StrictRedis(
  42. host=host,
  43. port=port,
  44. db=db,
  45. password=password or None,
  46. decode_responses=True,
  47. )
  48. def search(query, _params):
  49. if not exact_match_only:
  50. return search_keys(query)
  51. ret = _redis_client.hgetall(query)
  52. if ret:
  53. ret['template'] = result_template
  54. return [ret]
  55. if ' ' in query:
  56. qset, rest = query.split(' ', 1)
  57. ret = []
  58. for res in _redis_client.hscan_iter(qset, match='*{}*'.format(rest)):
  59. ret.append(
  60. {
  61. res[0]: res[1],
  62. 'template': result_template,
  63. }
  64. )
  65. return ret
  66. return []
  67. def search_keys(query):
  68. ret = []
  69. for key in _redis_client.scan_iter(match='*{}*'.format(query)):
  70. key_type = _redis_client.type(key)
  71. res = None
  72. if key_type == 'hash':
  73. res = _redis_client.hgetall(key)
  74. elif key_type == 'list':
  75. res = dict(enumerate(_redis_client.lrange(key, 0, -1)))
  76. if res:
  77. res['template'] = result_template
  78. res['redis_key'] = key
  79. ret.append(res)
  80. return ret