redisdb.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. from searx import get_setting
  19. logger = logging.getLogger('searx.shared.redis')
  20. _client = None
  21. def client():
  22. global _client # pylint: disable=global-statement
  23. import redis # pylint: disable=import-error, import-outside-toplevel
  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. import redis # pylint: disable=import-error, import-outside-toplevel
  31. try:
  32. c = client()
  33. logger.info("connected redis DB --> %s", c.acl_whoami())
  34. return True
  35. except redis.exceptions.ConnectionError as exc:
  36. logger.error("can't connet redis DB ...")
  37. logger.error(" %s", exc)
  38. return False