redisdb.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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.redisdb')
  23. _client = None
  24. def client() -> redis.Redis:
  25. return _client
  26. def initialize():
  27. global _client # pylint: disable=global-statement
  28. try:
  29. _client = redis.Redis.from_url(get_setting('redis.url'))
  30. logger.info("connected redis: %s", get_setting('redis.url'))
  31. except redis.exceptions.ConnectionError as exc:
  32. _pw = pwd.getpwuid(os.getuid())
  33. logger.error("[%s (%s)] can't connect redis DB ...", _pw.pw_name, _pw.pw_uid)
  34. logger.error(" %s", exc)