1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
|
from __future__ import annotations
from collections import defaultdict
from itertools import chain
from types import MappingProxyType
from typing import Any
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import Sequence
from typing import Union
from dynaconf import validator_conditions
from dynaconf.utils import ensure_a_list
from dynaconf.utils.functional import empty
EQUALITY_ATTRS = (
"names",
"must_exist",
"when",
"condition",
"operations",
"envs",
)
class ValidationError(Exception):
pass
class Validator:
"""Validators are conditions attached to settings variables names
or patterns::
Validator('MESSAGE', must_exist=True, eq='Hello World')
The above ensure MESSAGE is available in default env and
is equal to 'Hello World'
`names` are a one (or more) names or patterns::
Validator('NAME')
Validator('NAME', 'OTHER_NAME', 'EVEN_OTHER')
Validator(r'^NAME', r'OTHER./*')
The `operations` are::
eq: value == other
ne: value != other
gt: value > other
lt: value < other
gte: value >= other
lte: value <= other
is_type_of: isinstance(value, type)
is_in: value in sequence
is_not_in: value not in sequence
identity: value is other
cont: contain value in
len_eq: len(value) == other
len_ne: len(value) != other
len_min: len(value) > other
len_max: len(value) < other
`env` is which env to be checked, can be a list or
default is used.
`when` holds a validator and its return decides if validator runs or not::
Validator('NAME', must_exist=True, when=Validator('OTHER', eq=2))
# NAME is required only if OTHER eq to 2
# When the very first thing to be performed when passed.
# if no env is passed to `when` it is inherited
`must_exist` is alias to `required` requirement. (executed after when)::
settings.get(value, empty) returns non empty
condition is a callable to be executed and return boolean::
Validator('NAME', condition=lambda x: x == 1)
# it is executed before operations.
"""
default_messages = MappingProxyType(
{
"must_exist_true": "{name} is required in env {env}",
"must_exist_false": "{name} cannot exists in env {env}",
"condition": "{name} invalid for {function}({value}) in env {env}",
"operations": (
"{name} must {operation} {op_value} "
"but it is {value} in env {env}"
),
"combined": "combined validators failed {errors}",
}
)
def __init__(
self,
*names: str,
must_exist: Optional[bool] = None,
required: Optional[bool] = None, # alias for `must_exist`
condition: Optional[Callable[[Any], bool]] = None,
when: Optional[Validator] = None,
env: Optional[Union[str, Sequence[str]]] = None,
messages: Optional[Dict[str, str]] = None,
cast: Optional[Callable[[Any], Any]] = None,
default: Optional[Union[Any, Callable[[Any, Validator], Any]]] = empty,
description: Optional[str] = None,
**operations: Any,
) -> None:
# Copy immutable MappingProxyType as a mutable dict
self.messages = dict(self.default_messages)
if messages:
self.messages.update(messages)
if when is not None and not isinstance(when, Validator):
raise TypeError("when must be Validator instance")
if condition is not None and not callable(condition):
raise TypeError("condition must be callable")
self.names = names
self.must_exist = must_exist if must_exist is not None else required
self.condition = condition
self.when = when
self.cast = cast or (lambda value: value)
self.operations = operations
self.default = default
self.description = description
self.envs: Optional[Sequence[str]] = None
if isinstance(env, str):
self.envs = [env]
elif isinstance(env, (list, tuple)):
self.envs = env
def __or__(self, other: Validator) -> CombinedValidator:
return OrValidator(self, other, description=self.description)
def __and__(self, other: Validator) -> CombinedValidator:
return AndValidator(self, other, description=self.description)
def __eq__(self, other: object) -> bool:
if self is other:
return True
if type(self).__name__ != type(other).__name__:
return False
identical_attrs = (
getattr(self, attr) == getattr(other, attr)
for attr in EQUALITY_ATTRS
)
if all(identical_attrs):
return True
return False
def validate(
self,
settings: Any,
only: Optional[Union[str, Sequence]] = None,
exclude: Optional[Union[str, Sequence]] = None,
) -> None:
"""Raise ValidationError if invalid"""
# If only or exclude are not set, this value always passes startswith
only = ensure_a_list(only or [""])
if only and not isinstance(only[0], str):
raise ValueError("'only' must be a string or list of strings.")
exclude = ensure_a_list(exclude)
if exclude and not isinstance(exclude[0], str):
raise ValueError("'exclude' must be a string or list of strings.")
if self.envs is None:
self.envs = [settings.current_env]
if self.when is not None:
try:
# inherit env if not defined
if self.when.envs is None:
self.when.envs = self.envs
self.when.validate(settings, only=only, exclude=exclude)
except ValidationError:
# if when is invalid, return canceling validation flow
return
# If only using current_env, skip using_env decoration (reload)
if (
len(self.envs) == 1
and self.envs[0].upper() == settings.current_env.upper()
):
self._validate_items(
settings, settings.current_env, only=only, exclude=exclude
)
return
for env in self.envs:
self._validate_items(
settings.from_env(env), only=only, exclude=exclude
)
def _validate_items(
self,
settings: Any,
env: Optional[str] = None,
only: Optional[Union[str, Sequence]] = None,
exclude: Optional[Union[str, Sequence]] = None,
) -> None:
env = env or settings.current_env
for name in self.names:
# Skip if only is set and name isn't in the only list
if only and not any(name.startswith(sub) for sub in only):
continue
# Skip if exclude is set and name is in the exclude list
if exclude and any(name.startswith(sub) for sub in exclude):
continue
if self.default is not empty:
default_value = (
self.default(settings, self)
if callable(self.default)
else self.default
)
else:
default_value = empty
value = self.cast(settings.setdefault(name, default_value))
# is name required but not exists?
if self.must_exist is True and value is empty:
raise ValidationError(
self.messages["must_exist_true"].format(name=name, env=env)
)
if self.must_exist is False and value is not empty:
raise ValidationError(
self.messages["must_exist_false"].format(
name=name, env=env
)
)
if self.must_exist in (False, None) and value is empty:
continue
# is there a callable condition?
if self.condition is not None:
if not self.condition(value):
raise ValidationError(
self.messages["condition"].format(
name=name,
function=self.condition.__name__,
value=value,
env=env,
)
)
# operations
for op_name, op_value in self.operations.items():
op_function = getattr(validator_conditions, op_name)
if not op_function(value, op_value):
raise ValidationError(
self.messages["operations"].format(
name=name,
operation=op_function.__name__,
op_value=op_value,
value=value,
env=env,
)
)
class CombinedValidator(Validator):
def __init__(
self,
validator_a: Validator,
validator_b: Validator,
*args: Any,
**kwargs: Any,
) -> None:
"""Takes 2 validators and combines the validation"""
self.validators = (validator_a, validator_b)
super().__init__(*args, **kwargs)
for attr in EQUALITY_ATTRS:
if not getattr(self, attr, None):
value = tuple(
getattr(validator, attr) for validator in self.validators
)
setattr(self, attr, value)
def validate(
self,
settings: Any,
only: Optional[Union[str, Sequence]] = None,
exclude: Optional[Union[str, Sequence]] = None,
) -> None: # pragma: no cover
raise NotImplementedError(
"subclasses OrValidator or AndValidator implements this method"
)
class OrValidator(CombinedValidator):
"""Evaluates on Validator() | Validator()"""
def validate(
self,
settings: Any,
only: Optional[Union[str, Sequence]] = None,
exclude: Optional[Union[str, Sequence]] = None,
) -> None:
"""Ensure at least one of the validators are valid"""
errors = []
for validator in self.validators:
try:
validator.validate(settings, only=only, exclude=exclude)
except ValidationError as e:
errors.append(e)
continue
else:
return
raise ValidationError(
self.messages["combined"].format(
errors=" or ".join(
str(e).replace("combined validators failed ", "")
for e in errors
)
)
)
class AndValidator(CombinedValidator):
"""Evaluates on Validator() & Validator()"""
def validate(
self,
settings: Any,
only: Optional[Union[str, Sequence]] = None,
exclude: Optional[Union[str, Sequence]] = None,
) -> None:
"""Ensure both the validators are valid"""
errors = []
for validator in self.validators:
try:
validator.validate(settings, only=only, exclude=exclude)
except ValidationError as e:
errors.append(e)
continue
if errors:
raise ValidationError(
self.messages["combined"].format(
errors=" and ".join(
str(e).replace("combined validators failed ", "")
for e in errors
)
)
)
class ValidatorList(list):
def __init__(
self,
settings: Any,
validators: Optional[Sequence[Validator]] = None,
*args: Validator,
**kwargs: Any,
) -> None:
if isinstance(validators, (list, tuple)):
args = list(args) + list(validators) # type: ignore
self._only = kwargs.pop("validate_only", None)
self._exclude = kwargs.pop("validate_exclude", None)
super(ValidatorList, self).__init__(args, **kwargs) # type: ignore
self.settings = settings
def register(self, *args: Validator, **kwargs: Validator):
validators: List[Validator] = list(
chain.from_iterable(kwargs.values()) # type: ignore
)
validators.extend(args)
for validator in validators:
if validator and validator not in self:
self.append(validator)
def descriptions(
self, flat: bool = False
) -> Dict[str, Union[str, List[str]]]:
if flat:
descriptions: Dict[str, Union[str, List[str]]] = {}
else:
descriptions = defaultdict(list)
for validator in self:
for name in validator.names:
if isinstance(name, tuple) and len(name) > 0:
name = name[0]
if flat:
descriptions.setdefault(name, validator.description)
else:
descriptions[name].append( # type: ignore
validator.description
)
return descriptions
def validate(
self,
only: Optional[Union[str, Sequence]] = None,
exclude: Optional[Union[str, Sequence]] = None,
) -> None:
for validator in self:
validator.validate(self.settings, only=only, exclude=exclude)
|