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