searxng/searx/redisdb.py
Markus Heiser 86b4d2f2d0 [mod] activate pyright checks (in CI)
We have been using a static type checker (pyright) for a long time, but its
check was not yet a prerequisite for passing the quality gate.  It was checked
in the CI, but the error messages were only logged.

As is always the case in life, with checks that you have to do but which have no
consequences; you neglect them :-)

We didn't activate the checks back then because we (even today) have too much
monkey patching in our code (not only in the engines, httpx and others objects
are also affected).

We want to replace monkey patching with clear interfaces for a long time, the
basis for this is increased typing and we can only achieve this if we make type
checking an integral part of the quality gate.

  This PR activates the type check; in order to pass the check, a few typings
  were corrected in the code, but most type inconsistencies were deactivated via
  inline comments.

This was particularly necessary in places where the code uses properties that
stick to the objects (monkey patching).  The sticking of properties only happens
in a few places, but the access to these properties extends over the entire
code, which is why there are many `# type: ignore` markers in the code ... which
we will hopefully be able to remove again successively in the future.

Signed-off-by: Markus Heiser <markus.heiser@darmarit.de>
2024-04-27 18:31:52 +02:00

69 lines
2 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Implementation of the redis client (redis-py_).
.. _redis-py: https://github.com/redis/redis-py
This implementation uses the :ref:`settings redis` setup from ``settings.yml``.
A redis DB connect can be tested by::
>>> from searx import redisdb
>>> redisdb.initialize()
True
>>> db = redisdb.client()
>>> db.set("foo", "bar")
True
>>> db.get("foo")
b'bar'
>>>
"""
import os
import pwd
import logging
import redis
from searx import get_setting
OLD_REDIS_URL_DEFAULT_URL = 'unix:///usr/local/searxng-redis/run/redis.sock?db=0'
"""This was the default Redis URL in settings.yml."""
_CLIENT = None
logger = logging.getLogger(__name__)
def client() -> redis.Redis:
return _CLIENT # type: ignore
def initialize():
global _CLIENT # pylint: disable=global-statement
redis_url = get_setting('redis.url')
if not redis_url:
return False
try:
# create a client, but no connection is done
_CLIENT = redis.Redis.from_url(redis_url) # type: ignore
# log the parameters as seen by the redis lib, without the password
kwargs = _CLIENT.get_connection_kwargs().copy()
kwargs.pop('password', None)
kwargs = ' '.join([f'{k}={v!r}' for k, v in kwargs.items()])
logger.info("connecting to Redis %s", kwargs)
# check the connection
_CLIENT.ping()
# no error: the redis connection is working
logger.info("connected to Redis")
return True
except redis.exceptions.RedisError as e: # type: ignore
_CLIENT = None
_pw = pwd.getpwuid(os.getuid())
logger.exception("[%s (%s)] can't connect redis DB ...", _pw.pw_name, _pw.pw_uid)
if redis_url == OLD_REDIS_URL_DEFAULT_URL and isinstance(e, redis.exceptions.ConnectionError): # type: ignore
logger.info(
"You can safely ignore the above Redis error if you don't use Redis. "
"You can remove this error by setting redis.url to false in your settings.yml."
)
return False