redisdb.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Implementation of the redis client (redis-py_).
  3. .. _redis-py: https://github.com/redis/redis-py
  4. This implementation uses the :ref:`settings redis` setup from ``settings.yml``.
  5. A redis DB connect can be tested by::
  6. >>> from searx import redisdb
  7. >>> redisdb.initialize()
  8. True
  9. >>> db = redisdb.client()
  10. >>> db.set("foo", "bar")
  11. True
  12. >>> db.get("foo")
  13. b'bar'
  14. >>>
  15. """
  16. import os
  17. import pwd
  18. import logging
  19. import redis
  20. from searx import get_setting
  21. OLD_REDIS_URL_DEFAULT_URL = 'unix:///usr/local/searxng-redis/run/redis.sock?db=0'
  22. """This was the default Redis URL in settings.yml."""
  23. _CLIENT = None
  24. logger = logging.getLogger(__name__)
  25. def client() -> redis.Redis:
  26. return _CLIENT
  27. def initialize():
  28. global _CLIENT # pylint: disable=global-statement
  29. redis_url = get_setting('redis.url')
  30. if not redis_url:
  31. return False
  32. try:
  33. # create a client, but no connection is done
  34. _CLIENT = redis.Redis.from_url(redis_url)
  35. # log the parameters as seen by the redis lib, without the password
  36. kwargs = _CLIENT.get_connection_kwargs().copy()
  37. kwargs.pop('password', None)
  38. kwargs = ' '.join([f'{k}={v!r}' for k, v in kwargs.items()])
  39. logger.info("connecting to Redis %s", kwargs)
  40. # check the connection
  41. _CLIENT.ping()
  42. # no error: the redis connection is working
  43. logger.info("connected to Redis")
  44. return True
  45. except redis.exceptions.RedisError as e:
  46. _CLIENT = None
  47. _pw = pwd.getpwuid(os.getuid())
  48. logger.exception("[%s (%s)] can't connect redis DB ...", _pw.pw_name, _pw.pw_uid)
  49. if redis_url == OLD_REDIS_URL_DEFAULT_URL and isinstance(e, redis.exceptions.ConnectionError):
  50. logger.info(
  51. "You can safely ignore the above Redis error if you don't use Redis. "
  52. "You can remove this error by setting redis.url to false in your settings.yml."
  53. )
  54. return False