redis_server.py 2.3 KB

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