.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

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 257 of file config.py.

263) -> typing.Tuple[bool, typing.List]:
264
265 is_valid = True
266
267 for key, data_value in data_dict.items():
268
269 names.append(key)
270 name = '.'.join(names)
271
272 deprecated_msg = deprecated.get(name)
273 # print("XXX %s: key %s // data_value: %s" % (name, key, data_value))
274 if deprecated_msg:
275 issue_list.append(SchemaIssue('warn', f"data_dict '{name}': deprecated - {deprecated_msg}"))
276
277 schema_value = value(name, schema_dict)
278 # print("YYY %s: key %s // schema_value: %s" % (name, key, schema_value))
279 if schema_value is UNSET:
280 if not deprecated_msg:
281 issue_list.append(SchemaIssue('invalid', f"data_dict '{name}': key unknown in schema_dict"))
282 is_valid = False
283
284 elif type(schema_value) != type(data_value): # pylint: disable=unidiomatic-typecheck
285 issue_list.append(
286 SchemaIssue(
287 'invalid',
288 (f"data_dict: type mismatch '{name}':" f" expected {type(schema_value)}, is: {type(data_value)}"),
289 )
290 )
291 is_valid = False
292
293 elif isinstance(data_value, dict):
294 _valid, _ = _validate(names, issue_list, schema_dict, data_value, deprecated)
295 is_valid = is_valid and _valid
296 names.pop()
297
298 return is_valid, issue_list
299
300

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 301 of file config.py.

301def dict_deepupdate(base_dict: dict, upd_dict: dict, names=None):
302 """Deep-update of dictionary in ``base_dict`` by dictionary in ``upd_dict``.
303
304 For each ``upd_key`` & ``upd_val`` pair in ``upd_dict``:
305
306 0. If types of ``base_dict[upd_key]`` and ``upd_val`` do not match raise a
307 :py:obj:`TypeError`.
308
309 1. If ``base_dict[upd_key]`` is a dict: recursively deep-update it by ``upd_val``.
310
311 2. If ``base_dict[upd_key]`` not exist: set ``base_dict[upd_key]`` from a
312 (deep-) copy of ``upd_val``.
313
314 3. If ``upd_val`` is a list, extend list in ``base_dict[upd_key]`` by the
315 list in ``upd_val``.
316
317 4. If ``upd_val`` is a set, update set in ``base_dict[upd_key]`` by set in
318 ``upd_val``.
319 """
320 # pylint: disable=too-many-branches
321 if not isinstance(base_dict, dict):
322 raise TypeError("argument 'base_dict' is not a ditionary type")
323 if not isinstance(upd_dict, dict):
324 raise TypeError("argument 'upd_dict' is not a ditionary type")
325
326 if names is None:
327 names = []
328
329 for upd_key, upd_val in upd_dict.items():
330 # For each upd_key & upd_val pair in upd_dict:
331
332 if isinstance(upd_val, dict):
333
334 if upd_key in base_dict:
335 # if base_dict[upd_key] exists, recursively deep-update it
336 if not isinstance(base_dict[upd_key], dict):
337 raise TypeError(f"type mismatch {'.'.join(names)}: is not a dict type in base_dict")
338 dict_deepupdate(
339 base_dict[upd_key],
340 upd_val,
341 names
342 + [
343 upd_key,
344 ],
345 )
346
347 else:
348 # if base_dict[upd_key] not exist, set base_dict[upd_key] from deepcopy of upd_val
349 base_dict[upd_key] = copy.deepcopy(upd_val)
350
351 elif isinstance(upd_val, list):
352
353 if upd_key in base_dict:
354 # if base_dict[upd_key] exists, base_dict[up_key] is extended by
355 # the list from upd_val
356 if not isinstance(base_dict[upd_key], list):
357 raise TypeError(f"type mismatch {'.'.join(names)}: is not a list type in base_dict")
358 base_dict[upd_key].extend(upd_val)
359
360 else:
361 # if base_dict[upd_key] doesn't exists, set base_dict[key] from a deepcopy of the
362 # list in upd_val.
363 base_dict[upd_key] = copy.deepcopy(upd_val)
364
365 elif isinstance(upd_val, set):
366
367 if upd_key in base_dict:
368 # if base_dict[upd_key] exists, base_dict[up_key] is updated by the set in upd_val
369 if not isinstance(base_dict[upd_key], set):
370 raise TypeError(f"type mismatch {'.'.join(names)}: is not a set type in base_dict")
371 base_dict[upd_key].update(upd_val.copy())
372
373 else:
374 # if base_dict[upd_key] doesn't exists, set base_dict[upd_key] from a copy of the
375 # set in upd_val
376 base_dict[upd_key] = upd_val.copy()
377
378 else:
379 # for any other type of upd_val replace or add base_dict[upd_key] by a copy
380 # of upd_val
381 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 175 of file config.py.

175def toml_load(file_name):
176 try:
177 with open(file_name, "rb") as f:
178 return tomllib.load(f)
179 except tomllib.TOMLDecodeError as exc:
180 msg = str(exc).replace('\t', '').replace('\n', ' ')
181 log.error("%s: %s", file_name, msg)
182 raise
183
184
185# working with dictionaries
186
187

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 216 of file config.py.

218) -> typing.Tuple[bool, list]:
219 """Deep validation of dictionary in ``data_dict`` against dictionary in
220 ``schema_dict``. Argument deprecated is a dictionary that maps deprecated
221 configuration names to a messages::
222
223 deprecated = {
224 "foo.bar" : "config 'foo.bar' is deprecated, use 'bar.foo'",
225 "..." : "..."
226 }
227
228 The function returns a python tuple ``(is_valid, issue_list)``:
229
230 ``is_valid``:
231 A bool value indicating ``data_dict`` is valid or not.
232
233 ``issue_list``:
234 A list of messages (:py:obj:`SchemaIssue`) from the validation::
235
236 [schema warn] data_dict: deprecated 'fontlib.foo': <DEPRECATED['foo.bar']>
237 [schema invalid] data_dict: key unknown 'fontlib.foo'
238 [schema invalid] data_dict: type mismatch 'fontlib.foo': expected ..., is ...
239
240 If ``schema_dict`` or ``data_dict`` is not a dictionary type a
241 :py:obj:`SchemaIssue` is raised.
242
243 """
244 names = []
245 is_valid = True
246 issue_list = []
247
248 if not isinstance(schema_dict, dict):
249 raise SchemaIssue('invalid', "schema_dict is not a dict type")
250 if not isinstance(data_dict, dict):
251 raise SchemaIssue('invalid', f"data_dict issue{'.'.join(names)} is not a dict type")
252
253 is_valid, issue_list = _validate(names, issue_list, schema_dict, data_dict, deprecated)
254 return is_valid, issue_list
255
256

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 188 of file config.py.

188def value(name: str, data_dict: dict):
189 """Returns the value to which ``name`` points in the ``dat_dict``.
190
191 .. code: python
192
193 >>> data_dict = {
194 "foo": {"bar": 1 },
195 "bar": {"foo": 2 },
196 "foobar": [1, 2, 3],
197 }
198 >>> value('foobar', data_dict)
199 [1, 2, 3]
200 >>> value('foo.bar', data_dict)
201 1
202 >>> value('foo.bar.xxx', data_dict)
203 <UNSET>
204
205 """
206
207 ret_val = data_dict
208 for part in name.split('.'):
209 if isinstance(ret_val, dict):
210 ret_val = ret_val.get(part, UNSET)
211 if ret_val is UNSET:
212 break
213 return ret_val
214
215

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 19 of file config.py.

◆ log

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

Definition at line 21 of file config.py.

◆ UNSET

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

Definition at line 40 of file config.py.