redisdb.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 os
  18. import pwd
  19. import logging
  20. import redis
  21. from searx import get_setting
  22. logger = logging.getLogger('searx.shared.redis')
  23. _client = None
  24. def client():
  25. global _client # pylint: disable=global-statement
  26. if _client is None:
  27. # not thread safe: in the worst case scenario, two or more clients are
  28. # initialized only one is kept, the others are garbage collected.
  29. _client = redis.Redis.from_url(get_setting('redis.url'))
  30. return _client
  31. def init():
  32. try:
  33. c = client()
  34. logger.info("connected redis DB --> %s", c.acl_whoami())
  35. return True
  36. except redis.exceptions.ConnectionError as exc:
  37. _pw = pwd.getpwuid(os.getuid())
  38. logger.error("[%s (%s)] can't connect redis DB ...", _pw.pw_name, _pw.pw_uid)
  39. logger.error(" %s", exc)
  40. return False