redisdb.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Implementation of the redis client (redis-py_).
  4. .. _redis-py: https://github.com/redis/redis-py
  5. This implementation uses the :ref:`settings redis` setup from ``settings.yml``.
  6. A redis DB connect can be tested by::
  7. >>> from searx.shared import redisdb
  8. >>> redisdb.init()
  9. True
  10. >>> db = redisdb.client()
  11. >>> db.set("foo", "bar")
  12. True
  13. >>> db.get("foo")
  14. b'bar'
  15. >>>
  16. """
  17. import logging
  18. import redis
  19. from searx import get_setting
  20. logger = logging.getLogger('searx.shared.redis')
  21. _client = None
  22. def client():
  23. global _client # pylint: disable=global-statement
  24. if _client is None:
  25. # not thread safe: in the worst case scenario, two or more clients are
  26. # initialized only one is kept, the others are garbage collected.
  27. _client = redis.Redis.from_url(get_setting('redis.url'))
  28. return _client
  29. def init():
  30. try:
  31. c = client()
  32. logger.info("connected redis DB --> %s", c.acl_whoami())
  33. return True
  34. except redis.exceptions.ConnectionError as exc:
  35. logger.error("can't connet redis DB ...")
  36. logger.error(" %s", exc)
  37. return False