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