.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
searx.botdetection.config Namespace Reference

Classes

class  Config
 
class  FALSE
 
class  SchemaIssue
 

Functions

 toml_load (file_name)
 
 value (str name, dict data_dict)
 
typing.Tuple[bool, list] validate (typing.Dict schema_dict, typing.Dict data_dict, typing.Dict[str, str] deprecated)
 
typing.Tuple[bool, typing.List] _validate (typing.List names, typing.List issue_list, typing.Dict schema_dict, typing.Dict data_dict, typing.Dict[str, str] deprecated)
 
 dict_deepupdate (dict base_dict, dict upd_dict, names=None)
 

Variables

 pytomlpp = None
 
bool USE_TOMLLIB = True
 
 tomllib = None
 
list __all__ = ['Config', 'UNSET', 'SchemaIssue']
 
 log = logging.getLogger(__name__)
 
 UNSET = FALSE('<UNSET>')
 

Detailed Description

Configuration class :py:class:`Config` with deep-update, schema validation
and deprecated names.

The :py:class:`Config` class implements a configuration that is based on
structured dictionaries.  The configuration schema is defined in a dictionary
structure and the configuration data is given in a dictionary structure.

Function Documentation

◆ _validate()

typing.Tuple[bool, typing.List] searx.botdetection.config._validate ( typing.List names,
typing.List issue_list,
typing.Dict schema_dict,
typing.Dict data_dict,
typing.Dict[str, str] deprecated )
protected

Definition at line 276 of file config.py.

282) -> typing.Tuple[bool, typing.List]:
283
284 is_valid = True
285
286 for key, data_value in data_dict.items():
287
288 names.append(key)
289 name = '.'.join(names)
290
291 deprecated_msg = deprecated.get(name)
292 # print("XXX %s: key %s // data_value: %s" % (name, key, data_value))
293 if deprecated_msg:
294 issue_list.append(SchemaIssue('warn', f"data_dict '{name}': deprecated - {deprecated_msg}"))
295
296 schema_value = value(name, schema_dict)
297 # print("YYY %s: key %s // schema_value: %s" % (name, key, schema_value))
298 if schema_value is UNSET:
299 if not deprecated_msg:
300 issue_list.append(SchemaIssue('invalid', f"data_dict '{name}': key unknown in schema_dict"))
301 is_valid = False
302
303 elif type(schema_value) != type(data_value): # pylint: disable=unidiomatic-typecheck
304 issue_list.append(
305 SchemaIssue(
306 'invalid',
307 (f"data_dict: type mismatch '{name}':" f" expected {type(schema_value)}, is: {type(data_value)}"),
308 )
309 )
310 is_valid = False
311
312 elif isinstance(data_value, dict):
313 _valid, _ = _validate(names, issue_list, schema_dict, data_value, deprecated)
314 is_valid = is_valid and _valid
315 names.pop()
316
317 return is_valid, issue_list
318
319

References searx.botdetection.config._validate(), and searx.botdetection.config.value().

Referenced by searx.botdetection.config._validate(), and searx.botdetection.config.validate().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ dict_deepupdate()

searx.botdetection.config.dict_deepupdate ( dict base_dict,
dict upd_dict,
names = None )
Deep-update of dictionary in ``base_dict`` by dictionary in ``upd_dict``.

For each ``upd_key`` & ``upd_val`` pair in ``upd_dict``:

0. If types of ``base_dict[upd_key]`` and ``upd_val`` do not match raise a
   :py:obj:`TypeError`.

1. If ``base_dict[upd_key]`` is a dict: recursively deep-update it by ``upd_val``.

2. If ``base_dict[upd_key]`` not exist: set ``base_dict[upd_key]`` from a
   (deep-) copy of ``upd_val``.

3. If ``upd_val`` is a list, extend list in ``base_dict[upd_key]`` by the
   list in ``upd_val``.

4. If ``upd_val`` is a set, update set in ``base_dict[upd_key]`` by set in
   ``upd_val``.

Definition at line 320 of file config.py.

320def dict_deepupdate(base_dict: dict, upd_dict: dict, names=None):
321 """Deep-update of dictionary in ``base_dict`` by dictionary in ``upd_dict``.
322
323 For each ``upd_key`` & ``upd_val`` pair in ``upd_dict``:
324
325 0. If types of ``base_dict[upd_key]`` and ``upd_val`` do not match raise a
326 :py:obj:`TypeError`.
327
328 1. If ``base_dict[upd_key]`` is a dict: recursively deep-update it by ``upd_val``.
329
330 2. If ``base_dict[upd_key]`` not exist: set ``base_dict[upd_key]`` from a
331 (deep-) copy of ``upd_val``.
332
333 3. If ``upd_val`` is a list, extend list in ``base_dict[upd_key]`` by the
334 list in ``upd_val``.
335
336 4. If ``upd_val`` is a set, update set in ``base_dict[upd_key]`` by set in
337 ``upd_val``.
338 """
339 # pylint: disable=too-many-branches
340 if not isinstance(base_dict, dict):
341 raise TypeError("argument 'base_dict' is not a ditionary type")
342 if not isinstance(upd_dict, dict):
343 raise TypeError("argument 'upd_dict' is not a ditionary type")
344
345 if names is None:
346 names = []
347
348 for upd_key, upd_val in upd_dict.items():
349 # For each upd_key & upd_val pair in upd_dict:
350
351 if isinstance(upd_val, dict):
352
353 if upd_key in base_dict:
354 # if base_dict[upd_key] exists, recursively deep-update it
355 if not isinstance(base_dict[upd_key], dict):
356 raise TypeError(f"type mismatch {'.'.join(names)}: is not a dict type in base_dict")
357 dict_deepupdate(
358 base_dict[upd_key],
359 upd_val,
360 names
361 + [
362 upd_key,
363 ],
364 )
365
366 else:
367 # if base_dict[upd_key] not exist, set base_dict[upd_key] from deepcopy of upd_val
368 base_dict[upd_key] = copy.deepcopy(upd_val)
369
370 elif isinstance(upd_val, list):
371
372 if upd_key in base_dict:
373 # if base_dict[upd_key] exists, base_dict[up_key] is extended by
374 # the list from upd_val
375 if not isinstance(base_dict[upd_key], list):
376 raise TypeError(f"type mismatch {'.'.join(names)}: is not a list type in base_dict")
377 base_dict[upd_key].extend(upd_val)
378
379 else:
380 # if base_dict[upd_key] doesn't exists, set base_dict[key] from a deepcopy of the
381 # list in upd_val.
382 base_dict[upd_key] = copy.deepcopy(upd_val)
383
384 elif isinstance(upd_val, set):
385
386 if upd_key in base_dict:
387 # if base_dict[upd_key] exists, base_dict[up_key] is updated by the set in upd_val
388 if not isinstance(base_dict[upd_key], set):
389 raise TypeError(f"type mismatch {'.'.join(names)}: is not a set type in base_dict")
390 base_dict[upd_key].update(upd_val.copy())
391
392 else:
393 # if base_dict[upd_key] doesn't exists, set base_dict[upd_key] from a copy of the
394 # set in upd_val
395 base_dict[upd_key] = upd_val.copy()
396
397 else:
398 # for any other type of upd_val replace or add base_dict[upd_key] by a copy
399 # of upd_val
400 base_dict[upd_key] = copy.copy(upd_val)

References searx.botdetection.config.dict_deepupdate().

Referenced by searx.botdetection.config.dict_deepupdate(), and searx.botdetection.config.Config.update().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ toml_load()

searx.botdetection.config.toml_load ( file_name)

Definition at line 185 of file config.py.

185def toml_load(file_name):
186 if USE_TOMLLIB:
187 # Python >= 3.11
188 try:
189 with open(file_name, "rb") as f:
190 return tomllib.load(f)
191 except tomllib.TOMLDecodeError as exc:
192 msg = str(exc).replace('\t', '').replace('\n', ' ')
193 log.error("%s: %s", file_name, msg)
194 raise
195 # fallback to pytomlpp for Python < 3.11
196 try:
197 return pytomlpp.load(file_name)
198 except pytomlpp.DecodeError as exc:
199 msg = str(exc).replace('\t', '').replace('\n', ' ')
200 log.error("%s: %s", file_name, msg)
201 raise
202
203
204# working with dictionaries
205
206

Referenced by searx.botdetection.config.Config.from_toml().

+ Here is the caller graph for this function:

◆ validate()

typing.Tuple[bool, list] searx.botdetection.config.validate ( typing.Dict schema_dict,
typing.Dict data_dict,
typing.Dict[str, str] deprecated )
Deep validation of dictionary in ``data_dict`` against dictionary in
``schema_dict``.  Argument deprecated is a dictionary that maps deprecated
configuration names to a messages::

    deprecated = {
        "foo.bar" : "config 'foo.bar' is deprecated, use 'bar.foo'",
        "..."     : "..."
    }

The function returns a python tuple ``(is_valid, issue_list)``:

``is_valid``:
  A bool value indicating ``data_dict`` is valid or not.

``issue_list``:
  A list of messages (:py:obj:`SchemaIssue`) from the validation::

      [schema warn] data_dict: deprecated 'fontlib.foo': <DEPRECATED['foo.bar']>
      [schema invalid] data_dict: key unknown 'fontlib.foo'
      [schema invalid] data_dict: type mismatch 'fontlib.foo': expected ..., is ...

If ``schema_dict`` or ``data_dict`` is not a dictionary type a
:py:obj:`SchemaIssue` is raised.

Definition at line 235 of file config.py.

237) -> typing.Tuple[bool, list]:
238 """Deep validation of dictionary in ``data_dict`` against dictionary in
239 ``schema_dict``. Argument deprecated is a dictionary that maps deprecated
240 configuration names to a messages::
241
242 deprecated = {
243 "foo.bar" : "config 'foo.bar' is deprecated, use 'bar.foo'",
244 "..." : "..."
245 }
246
247 The function returns a python tuple ``(is_valid, issue_list)``:
248
249 ``is_valid``:
250 A bool value indicating ``data_dict`` is valid or not.
251
252 ``issue_list``:
253 A list of messages (:py:obj:`SchemaIssue`) from the validation::
254
255 [schema warn] data_dict: deprecated 'fontlib.foo': <DEPRECATED['foo.bar']>
256 [schema invalid] data_dict: key unknown 'fontlib.foo'
257 [schema invalid] data_dict: type mismatch 'fontlib.foo': expected ..., is ...
258
259 If ``schema_dict`` or ``data_dict`` is not a dictionary type a
260 :py:obj:`SchemaIssue` is raised.
261
262 """
263 names = []
264 is_valid = True
265 issue_list = []
266
267 if not isinstance(schema_dict, dict):
268 raise SchemaIssue('invalid', "schema_dict is not a dict type")
269 if not isinstance(data_dict, dict):
270 raise SchemaIssue('invalid', f"data_dict issue{'.'.join(names)} is not a dict type")
271
272 is_valid, issue_list = _validate(names, issue_list, schema_dict, data_dict, deprecated)
273 return is_valid, issue_list
274
275

References searx.botdetection.config._validate().

+ Here is the call graph for this function:

◆ value()

searx.botdetection.config.value ( str name,
dict data_dict )
Returns the value to which ``name`` points in the ``dat_dict``.

.. code: python

    >>> data_dict = {
            "foo": {"bar": 1 },
            "bar": {"foo": 2 },
            "foobar": [1, 2, 3],
        }
    >>> value('foobar', data_dict)
    [1, 2, 3]
    >>> value('foo.bar', data_dict)
    1
    >>> value('foo.bar.xxx', data_dict)
    <UNSET>

Definition at line 207 of file config.py.

207def value(name: str, data_dict: dict):
208 """Returns the value to which ``name`` points in the ``dat_dict``.
209
210 .. code: python
211
212 >>> data_dict = {
213 "foo": {"bar": 1 },
214 "bar": {"foo": 2 },
215 "foobar": [1, 2, 3],
216 }
217 >>> value('foobar', data_dict)
218 [1, 2, 3]
219 >>> value('foo.bar', data_dict)
220 1
221 >>> value('foo.bar.xxx', data_dict)
222 <UNSET>
223
224 """
225
226 ret_val = data_dict
227 for part in name.split('.'):
228 if isinstance(ret_val, dict):
229 ret_val = ret_val.get(part, UNSET)
230 if ret_val is UNSET:
231 break
232 return ret_val
233
234

Referenced by searx.botdetection.config.Config._get_parent_dict(), searx.botdetection.config._validate(), and searx.botdetection.config.Config.default().

+ Here is the caller graph for this function:

Variable Documentation

◆ __all__

list searx.botdetection.config.__all__ = ['Config', 'UNSET', 'SchemaIssue']
private

Definition at line 29 of file config.py.

◆ log

searx.botdetection.config.log = logging.getLogger(__name__)

Definition at line 31 of file config.py.

◆ pytomlpp

searx.botdetection.config.pytomlpp = None

Definition at line 20 of file config.py.

◆ tomllib

searx.botdetection.config.tomllib = None

Definition at line 25 of file config.py.

◆ UNSET

searx.botdetection.config.UNSET = FALSE('<UNSET>')

Definition at line 50 of file config.py.

◆ USE_TOMLLIB

bool searx.botdetection.config.USE_TOMLLIB = True

Definition at line 21 of file config.py.