pboot-validator 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pboot_validator/__init__.py +461 -0
- pboot_validator/_internal/__init__.py +0 -0
- pboot_validator/_internal/_config.py +408 -0
- pboot_validator/_internal/_contextlib.py +84 -0
- pboot_validator/_internal/_core_metadata.py +97 -0
- pboot_validator/_internal/_core_utils.py +156 -0
- pboot_validator/_internal/_dataclasses.py +327 -0
- pboot_validator/_internal/_decorators.py +906 -0
- pboot_validator/_internal/_decorators_v1.py +174 -0
- pboot_validator/_internal/_discriminated_union.py +510 -0
- pboot_validator/_internal/_docs_extraction.py +128 -0
- pboot_validator/_internal/_fields.py +910 -0
- pboot_validator/_internal/_forward_ref.py +23 -0
- pboot_validator/_internal/_generate_schema.py +3053 -0
- pboot_validator/_internal/_generics.py +572 -0
- pboot_validator/_internal/_git.py +27 -0
- pboot_validator/_internal/_import_utils.py +20 -0
- pboot_validator/_internal/_known_annotated_metadata.py +412 -0
- pboot_validator/_internal/_mock_val_ser.py +241 -0
- pboot_validator/_internal/_model_construction.py +833 -0
- pboot_validator/_internal/_namespace_utils.py +300 -0
- pboot_validator/_internal/_repr.py +129 -0
- pboot_validator/_internal/_schema_gather.py +49 -0
- pboot_validator/_internal/_schema_generation_shared.py +126 -0
- pboot_validator/_internal/_serializers.py +59 -0
- pboot_validator/_internal/_signature.py +193 -0
- pboot_validator/_internal/_type_refs.py +128 -0
- pboot_validator/_internal/_typing_extra.py +506 -0
- pboot_validator/_internal/_utils.py +433 -0
- pboot_validator/_internal/_validate_call.py +141 -0
- pboot_validator/_internal/_validators.py +541 -0
- pboot_validator/_migration.py +317 -0
- pboot_validator/alias_generators.py +62 -0
- pboot_validator/aliases.py +136 -0
- pboot_validator/annotated_handlers.py +123 -0
- pboot_validator/class_validators.py +5 -0
- pboot_validator/color.py +605 -0
- pboot_validator/config.py +1295 -0
- pboot_validator/dataclasses.py +385 -0
- pboot_validator/datetime_parse.py +5 -0
- pboot_validator/decorator.py +5 -0
- pboot_validator/deprecated/__init__.py +0 -0
- pboot_validator/deprecated/class_validators.py +257 -0
- pboot_validator/deprecated/config.py +72 -0
- pboot_validator/deprecated/copy_internals.py +224 -0
- pboot_validator/deprecated/decorator.py +286 -0
- pboot_validator/deprecated/json.py +142 -0
- pboot_validator/deprecated/parse.py +81 -0
- pboot_validator/deprecated/tools.py +104 -0
- pboot_validator/env_settings.py +5 -0
- pboot_validator/error_wrappers.py +5 -0
- pboot_validator/errors.py +185 -0
- pboot_validator/experimental/__init__.py +1 -0
- pboot_validator/experimental/arguments_schema.py +44 -0
- pboot_validator/experimental/missing_sentinel.py +29 -0
- pboot_validator/experimental/pipeline.py +684 -0
- pboot_validator/fields.py +2065 -0
- pboot_validator/functional_serializers.py +461 -0
- pboot_validator/functional_validators.py +920 -0
- pboot_validator/generics.py +5 -0
- pboot_validator/json.py +5 -0
- pboot_validator/json_schema.py +3283 -0
- pboot_validator/main.py +1947 -0
- pboot_validator/mypy.py +1469 -0
- pboot_validator/networks.py +1417 -0
- pboot_validator/parse.py +5 -0
- pboot_validator/plugin/__init__.py +190 -0
- pboot_validator/plugin/_loader.py +56 -0
- pboot_validator/plugin/_schema_validator.py +152 -0
- pboot_validator/py.typed +0 -0
- pboot_validator/root_model.py +189 -0
- pboot_validator/schema.py +5 -0
- pboot_validator/tools.py +5 -0
- pboot_validator/type_adapter.py +780 -0
- pboot_validator/types.py +3405 -0
- pboot_validator/typing.py +5 -0
- pboot_validator/utils.py +5 -0
- pboot_validator/v1/__init__.py +131 -0
- pboot_validator/v1/_hypothesis_plugin.py +391 -0
- pboot_validator/v1/annotated_types.py +72 -0
- pboot_validator/v1/class_validators.py +361 -0
- pboot_validator/v1/color.py +494 -0
- pboot_validator/v1/config.py +191 -0
- pboot_validator/v1/dataclasses.py +503 -0
- pboot_validator/v1/datetime_parse.py +248 -0
- pboot_validator/v1/decorator.py +264 -0
- pboot_validator/v1/env_settings.py +350 -0
- pboot_validator/v1/error_wrappers.py +161 -0
- pboot_validator/v1/errors.py +646 -0
- pboot_validator/v1/fields.py +1253 -0
- pboot_validator/v1/generics.py +400 -0
- pboot_validator/v1/json.py +112 -0
- pboot_validator/v1/main.py +1130 -0
- pboot_validator/v1/mypy.py +950 -0
- pboot_validator/v1/networks.py +747 -0
- pboot_validator/v1/parse.py +66 -0
- pboot_validator/v1/py.typed +0 -0
- pboot_validator/v1/schema.py +1163 -0
- pboot_validator/v1/tools.py +92 -0
- pboot_validator/v1/types.py +1213 -0
- pboot_validator/v1/typing.py +627 -0
- pboot_validator/v1/utils.py +807 -0
- pboot_validator/v1/validators.py +768 -0
- pboot_validator/v1/version.py +38 -0
- pboot_validator/validate_call_decorator.py +121 -0
- pboot_validator/validators.py +5 -0
- pboot_validator/version.py +113 -0
- pboot_validator/warnings.py +130 -0
- pboot_validator-1.0.0.dist-info/METADATA +93 -0
- pboot_validator-1.0.0.dist-info/RECORD +112 -0
- pboot_validator-1.0.0.dist-info/WHEEL +4 -0
- pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1213 @@
|
|
|
1
|
+
import abc
|
|
2
|
+
import math
|
|
3
|
+
import re
|
|
4
|
+
import warnings
|
|
5
|
+
from datetime import date
|
|
6
|
+
from decimal import Decimal, InvalidOperation
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from types import new_class
|
|
10
|
+
from typing import (
|
|
11
|
+
TYPE_CHECKING,
|
|
12
|
+
Any,
|
|
13
|
+
Callable,
|
|
14
|
+
ClassVar,
|
|
15
|
+
Dict,
|
|
16
|
+
FrozenSet,
|
|
17
|
+
List,
|
|
18
|
+
Optional,
|
|
19
|
+
Pattern,
|
|
20
|
+
Set,
|
|
21
|
+
Tuple,
|
|
22
|
+
Type,
|
|
23
|
+
TypeVar,
|
|
24
|
+
Union,
|
|
25
|
+
cast,
|
|
26
|
+
overload,
|
|
27
|
+
)
|
|
28
|
+
from uuid import UUID
|
|
29
|
+
from weakref import WeakSet
|
|
30
|
+
|
|
31
|
+
from pboot_validator.v1 import errors
|
|
32
|
+
from pboot_validator.v1.datetime_parse import parse_date
|
|
33
|
+
from pboot_validator.v1.utils import import_string, update_not_none
|
|
34
|
+
from pboot_validator.v1.validators import (
|
|
35
|
+
bytes_validator,
|
|
36
|
+
constr_length_validator,
|
|
37
|
+
constr_lower,
|
|
38
|
+
constr_strip_whitespace,
|
|
39
|
+
constr_upper,
|
|
40
|
+
decimal_validator,
|
|
41
|
+
float_finite_validator,
|
|
42
|
+
float_validator,
|
|
43
|
+
frozenset_validator,
|
|
44
|
+
int_validator,
|
|
45
|
+
list_validator,
|
|
46
|
+
number_multiple_validator,
|
|
47
|
+
number_size_validator,
|
|
48
|
+
path_exists_validator,
|
|
49
|
+
path_validator,
|
|
50
|
+
set_validator,
|
|
51
|
+
str_validator,
|
|
52
|
+
strict_bytes_validator,
|
|
53
|
+
strict_float_validator,
|
|
54
|
+
strict_int_validator,
|
|
55
|
+
strict_str_validator,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
__all__ = [
|
|
59
|
+
'NoneStr',
|
|
60
|
+
'NoneBytes',
|
|
61
|
+
'StrBytes',
|
|
62
|
+
'NoneStrBytes',
|
|
63
|
+
'StrictStr',
|
|
64
|
+
'ConstrainedBytes',
|
|
65
|
+
'conbytes',
|
|
66
|
+
'ConstrainedList',
|
|
67
|
+
'conlist',
|
|
68
|
+
'ConstrainedSet',
|
|
69
|
+
'conset',
|
|
70
|
+
'ConstrainedFrozenSet',
|
|
71
|
+
'confrozenset',
|
|
72
|
+
'ConstrainedStr',
|
|
73
|
+
'constr',
|
|
74
|
+
'PyObject',
|
|
75
|
+
'ConstrainedInt',
|
|
76
|
+
'conint',
|
|
77
|
+
'PositiveInt',
|
|
78
|
+
'NegativeInt',
|
|
79
|
+
'NonNegativeInt',
|
|
80
|
+
'NonPositiveInt',
|
|
81
|
+
'ConstrainedFloat',
|
|
82
|
+
'confloat',
|
|
83
|
+
'PositiveFloat',
|
|
84
|
+
'NegativeFloat',
|
|
85
|
+
'NonNegativeFloat',
|
|
86
|
+
'NonPositiveFloat',
|
|
87
|
+
'FiniteFloat',
|
|
88
|
+
'ConstrainedDecimal',
|
|
89
|
+
'condecimal',
|
|
90
|
+
'UUID1',
|
|
91
|
+
'UUID3',
|
|
92
|
+
'UUID4',
|
|
93
|
+
'UUID5',
|
|
94
|
+
'FilePath',
|
|
95
|
+
'DirectoryPath',
|
|
96
|
+
'Json',
|
|
97
|
+
'JsonWrapper',
|
|
98
|
+
'SecretField',
|
|
99
|
+
'SecretStr',
|
|
100
|
+
'SecretBytes',
|
|
101
|
+
'StrictBool',
|
|
102
|
+
'StrictBytes',
|
|
103
|
+
'StrictInt',
|
|
104
|
+
'StrictFloat',
|
|
105
|
+
'PaymentCardNumber',
|
|
106
|
+
'ByteSize',
|
|
107
|
+
'PastDate',
|
|
108
|
+
'FutureDate',
|
|
109
|
+
'ConstrainedDate',
|
|
110
|
+
'condate',
|
|
111
|
+
]
|
|
112
|
+
|
|
113
|
+
NoneStr = Optional[str]
|
|
114
|
+
NoneBytes = Optional[bytes]
|
|
115
|
+
StrBytes = Union[str, bytes]
|
|
116
|
+
NoneStrBytes = Optional[StrBytes]
|
|
117
|
+
OptionalInt = Optional[int]
|
|
118
|
+
OptionalIntFloat = Union[OptionalInt, float]
|
|
119
|
+
OptionalIntFloatDecimal = Union[OptionalIntFloat, Decimal]
|
|
120
|
+
OptionalDate = Optional[date]
|
|
121
|
+
StrIntFloat = Union[str, int, float]
|
|
122
|
+
|
|
123
|
+
if TYPE_CHECKING:
|
|
124
|
+
from typing_extensions import Annotated
|
|
125
|
+
|
|
126
|
+
from pboot_validator.v1.dataclasses import Dataclass
|
|
127
|
+
from pboot_validator.v1.main import BaseModel
|
|
128
|
+
from pboot_validator.v1.typing import CallableGenerator
|
|
129
|
+
|
|
130
|
+
ModelOrDc = Type[Union[BaseModel, Dataclass]]
|
|
131
|
+
|
|
132
|
+
T = TypeVar('T')
|
|
133
|
+
_DEFINED_TYPES: 'WeakSet[type]' = WeakSet()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@overload
|
|
137
|
+
def _registered(typ: Type[T]) -> Type[T]:
|
|
138
|
+
pass
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@overload
|
|
142
|
+
def _registered(typ: 'ConstrainedNumberMeta') -> 'ConstrainedNumberMeta':
|
|
143
|
+
pass
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _registered(typ: Union[Type[T], 'ConstrainedNumberMeta']) -> Union[Type[T], 'ConstrainedNumberMeta']:
|
|
147
|
+
# In order to generate valid examples of constrained types, Hypothesis needs
|
|
148
|
+
# to inspect the type object - so we keep a weakref to each contype object
|
|
149
|
+
# until it can be registered. When (or if) our Hypothesis plugin is loaded,
|
|
150
|
+
# it monkeypatches this function.
|
|
151
|
+
# If Hypothesis is never used, the total effect is to keep a weak reference
|
|
152
|
+
# which has minimal memory usage and doesn't even affect garbage collection.
|
|
153
|
+
_DEFINED_TYPES.add(typ)
|
|
154
|
+
return typ
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class ConstrainedNumberMeta(type):
|
|
158
|
+
def __new__(cls, name: str, bases: Any, dct: Dict[str, Any]) -> 'ConstrainedInt': # type: ignore
|
|
159
|
+
new_cls = cast('ConstrainedInt', type.__new__(cls, name, bases, dct))
|
|
160
|
+
|
|
161
|
+
if new_cls.gt is not None and new_cls.ge is not None:
|
|
162
|
+
raise errors.ConfigError('bounds gt and ge cannot be specified at the same time')
|
|
163
|
+
if new_cls.lt is not None and new_cls.le is not None:
|
|
164
|
+
raise errors.ConfigError('bounds lt and le cannot be specified at the same time')
|
|
165
|
+
|
|
166
|
+
return _registered(new_cls) # type: ignore
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BOOLEAN TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
170
|
+
|
|
171
|
+
if TYPE_CHECKING:
|
|
172
|
+
StrictBool = bool
|
|
173
|
+
else:
|
|
174
|
+
|
|
175
|
+
class StrictBool(int):
|
|
176
|
+
"""
|
|
177
|
+
StrictBool to allow for bools which are not type-coerced.
|
|
178
|
+
"""
|
|
179
|
+
|
|
180
|
+
@classmethod
|
|
181
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
182
|
+
field_schema.update(type='boolean')
|
|
183
|
+
|
|
184
|
+
@classmethod
|
|
185
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
186
|
+
yield cls.validate
|
|
187
|
+
|
|
188
|
+
@classmethod
|
|
189
|
+
def validate(cls, value: Any) -> bool:
|
|
190
|
+
"""
|
|
191
|
+
Ensure that we only allow bools.
|
|
192
|
+
"""
|
|
193
|
+
if isinstance(value, bool):
|
|
194
|
+
return value
|
|
195
|
+
|
|
196
|
+
raise errors.StrictBoolError()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ INTEGER TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class ConstrainedInt(int, metaclass=ConstrainedNumberMeta):
|
|
203
|
+
strict: bool = False
|
|
204
|
+
gt: OptionalInt = None
|
|
205
|
+
ge: OptionalInt = None
|
|
206
|
+
lt: OptionalInt = None
|
|
207
|
+
le: OptionalInt = None
|
|
208
|
+
multiple_of: OptionalInt = None
|
|
209
|
+
|
|
210
|
+
@classmethod
|
|
211
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
212
|
+
update_not_none(
|
|
213
|
+
field_schema,
|
|
214
|
+
exclusiveMinimum=cls.gt,
|
|
215
|
+
exclusiveMaximum=cls.lt,
|
|
216
|
+
minimum=cls.ge,
|
|
217
|
+
maximum=cls.le,
|
|
218
|
+
multipleOf=cls.multiple_of,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
@classmethod
|
|
222
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
223
|
+
yield strict_int_validator if cls.strict else int_validator
|
|
224
|
+
yield number_size_validator
|
|
225
|
+
yield number_multiple_validator
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def conint(
|
|
229
|
+
*,
|
|
230
|
+
strict: bool = False,
|
|
231
|
+
gt: Optional[int] = None,
|
|
232
|
+
ge: Optional[int] = None,
|
|
233
|
+
lt: Optional[int] = None,
|
|
234
|
+
le: Optional[int] = None,
|
|
235
|
+
multiple_of: Optional[int] = None,
|
|
236
|
+
) -> Type[int]:
|
|
237
|
+
# use kwargs then define conf in a dict to aid with IDE type hinting
|
|
238
|
+
namespace = dict(strict=strict, gt=gt, ge=ge, lt=lt, le=le, multiple_of=multiple_of)
|
|
239
|
+
return type('ConstrainedIntValue', (ConstrainedInt,), namespace)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
if TYPE_CHECKING:
|
|
243
|
+
PositiveInt = int
|
|
244
|
+
NegativeInt = int
|
|
245
|
+
NonPositiveInt = int
|
|
246
|
+
NonNegativeInt = int
|
|
247
|
+
StrictInt = int
|
|
248
|
+
else:
|
|
249
|
+
|
|
250
|
+
class PositiveInt(ConstrainedInt):
|
|
251
|
+
gt = 0
|
|
252
|
+
|
|
253
|
+
class NegativeInt(ConstrainedInt):
|
|
254
|
+
lt = 0
|
|
255
|
+
|
|
256
|
+
class NonPositiveInt(ConstrainedInt):
|
|
257
|
+
le = 0
|
|
258
|
+
|
|
259
|
+
class NonNegativeInt(ConstrainedInt):
|
|
260
|
+
ge = 0
|
|
261
|
+
|
|
262
|
+
class StrictInt(ConstrainedInt):
|
|
263
|
+
strict = True
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FLOAT TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class ConstrainedFloat(float, metaclass=ConstrainedNumberMeta):
|
|
270
|
+
strict: bool = False
|
|
271
|
+
gt: OptionalIntFloat = None
|
|
272
|
+
ge: OptionalIntFloat = None
|
|
273
|
+
lt: OptionalIntFloat = None
|
|
274
|
+
le: OptionalIntFloat = None
|
|
275
|
+
multiple_of: OptionalIntFloat = None
|
|
276
|
+
allow_inf_nan: Optional[bool] = None
|
|
277
|
+
|
|
278
|
+
@classmethod
|
|
279
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
280
|
+
update_not_none(
|
|
281
|
+
field_schema,
|
|
282
|
+
exclusiveMinimum=cls.gt,
|
|
283
|
+
exclusiveMaximum=cls.lt,
|
|
284
|
+
minimum=cls.ge,
|
|
285
|
+
maximum=cls.le,
|
|
286
|
+
multipleOf=cls.multiple_of,
|
|
287
|
+
)
|
|
288
|
+
# Modify constraints to account for differences between IEEE floats and JSON
|
|
289
|
+
if field_schema.get('exclusiveMinimum') == -math.inf:
|
|
290
|
+
del field_schema['exclusiveMinimum']
|
|
291
|
+
if field_schema.get('minimum') == -math.inf:
|
|
292
|
+
del field_schema['minimum']
|
|
293
|
+
if field_schema.get('exclusiveMaximum') == math.inf:
|
|
294
|
+
del field_schema['exclusiveMaximum']
|
|
295
|
+
if field_schema.get('maximum') == math.inf:
|
|
296
|
+
del field_schema['maximum']
|
|
297
|
+
|
|
298
|
+
@classmethod
|
|
299
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
300
|
+
yield strict_float_validator if cls.strict else float_validator
|
|
301
|
+
yield number_size_validator
|
|
302
|
+
yield number_multiple_validator
|
|
303
|
+
yield float_finite_validator
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def confloat(
|
|
307
|
+
*,
|
|
308
|
+
strict: bool = False,
|
|
309
|
+
gt: float = None,
|
|
310
|
+
ge: float = None,
|
|
311
|
+
lt: float = None,
|
|
312
|
+
le: float = None,
|
|
313
|
+
multiple_of: float = None,
|
|
314
|
+
allow_inf_nan: Optional[bool] = None,
|
|
315
|
+
) -> Type[float]:
|
|
316
|
+
# use kwargs then define conf in a dict to aid with IDE type hinting
|
|
317
|
+
namespace = dict(strict=strict, gt=gt, ge=ge, lt=lt, le=le, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan)
|
|
318
|
+
return type('ConstrainedFloatValue', (ConstrainedFloat,), namespace)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
if TYPE_CHECKING:
|
|
322
|
+
PositiveFloat = float
|
|
323
|
+
NegativeFloat = float
|
|
324
|
+
NonPositiveFloat = float
|
|
325
|
+
NonNegativeFloat = float
|
|
326
|
+
StrictFloat = float
|
|
327
|
+
FiniteFloat = float
|
|
328
|
+
else:
|
|
329
|
+
|
|
330
|
+
class PositiveFloat(ConstrainedFloat):
|
|
331
|
+
gt = 0
|
|
332
|
+
|
|
333
|
+
class NegativeFloat(ConstrainedFloat):
|
|
334
|
+
lt = 0
|
|
335
|
+
|
|
336
|
+
class NonPositiveFloat(ConstrainedFloat):
|
|
337
|
+
le = 0
|
|
338
|
+
|
|
339
|
+
class NonNegativeFloat(ConstrainedFloat):
|
|
340
|
+
ge = 0
|
|
341
|
+
|
|
342
|
+
class StrictFloat(ConstrainedFloat):
|
|
343
|
+
strict = True
|
|
344
|
+
|
|
345
|
+
class FiniteFloat(ConstrainedFloat):
|
|
346
|
+
allow_inf_nan = False
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BYTES TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
class ConstrainedBytes(bytes):
|
|
353
|
+
strip_whitespace = False
|
|
354
|
+
to_upper = False
|
|
355
|
+
to_lower = False
|
|
356
|
+
min_length: OptionalInt = None
|
|
357
|
+
max_length: OptionalInt = None
|
|
358
|
+
strict: bool = False
|
|
359
|
+
|
|
360
|
+
@classmethod
|
|
361
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
362
|
+
update_not_none(field_schema, minLength=cls.min_length, maxLength=cls.max_length)
|
|
363
|
+
|
|
364
|
+
@classmethod
|
|
365
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
366
|
+
yield strict_bytes_validator if cls.strict else bytes_validator
|
|
367
|
+
yield constr_strip_whitespace
|
|
368
|
+
yield constr_upper
|
|
369
|
+
yield constr_lower
|
|
370
|
+
yield constr_length_validator
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def conbytes(
|
|
374
|
+
*,
|
|
375
|
+
strip_whitespace: bool = False,
|
|
376
|
+
to_upper: bool = False,
|
|
377
|
+
to_lower: bool = False,
|
|
378
|
+
min_length: Optional[int] = None,
|
|
379
|
+
max_length: Optional[int] = None,
|
|
380
|
+
strict: bool = False,
|
|
381
|
+
) -> Type[bytes]:
|
|
382
|
+
# use kwargs then define conf in a dict to aid with IDE type hinting
|
|
383
|
+
namespace = dict(
|
|
384
|
+
strip_whitespace=strip_whitespace,
|
|
385
|
+
to_upper=to_upper,
|
|
386
|
+
to_lower=to_lower,
|
|
387
|
+
min_length=min_length,
|
|
388
|
+
max_length=max_length,
|
|
389
|
+
strict=strict,
|
|
390
|
+
)
|
|
391
|
+
return _registered(type('ConstrainedBytesValue', (ConstrainedBytes,), namespace))
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
if TYPE_CHECKING:
|
|
395
|
+
StrictBytes = bytes
|
|
396
|
+
else:
|
|
397
|
+
|
|
398
|
+
class StrictBytes(ConstrainedBytes):
|
|
399
|
+
strict = True
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ STRING TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
class ConstrainedStr(str):
|
|
406
|
+
strip_whitespace = False
|
|
407
|
+
to_upper = False
|
|
408
|
+
to_lower = False
|
|
409
|
+
min_length: OptionalInt = None
|
|
410
|
+
max_length: OptionalInt = None
|
|
411
|
+
curtail_length: OptionalInt = None
|
|
412
|
+
regex: Optional[Union[str, Pattern[str]]] = None
|
|
413
|
+
strict = False
|
|
414
|
+
|
|
415
|
+
@classmethod
|
|
416
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
417
|
+
update_not_none(
|
|
418
|
+
field_schema,
|
|
419
|
+
minLength=cls.min_length,
|
|
420
|
+
maxLength=cls.max_length,
|
|
421
|
+
pattern=cls.regex and cls._get_pattern(cls.regex),
|
|
422
|
+
)
|
|
423
|
+
|
|
424
|
+
@classmethod
|
|
425
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
426
|
+
yield strict_str_validator if cls.strict else str_validator
|
|
427
|
+
yield constr_strip_whitespace
|
|
428
|
+
yield constr_upper
|
|
429
|
+
yield constr_lower
|
|
430
|
+
yield constr_length_validator
|
|
431
|
+
yield cls.validate
|
|
432
|
+
|
|
433
|
+
@classmethod
|
|
434
|
+
def validate(cls, value: Union[str]) -> Union[str]:
|
|
435
|
+
if cls.curtail_length and len(value) > cls.curtail_length:
|
|
436
|
+
value = value[: cls.curtail_length]
|
|
437
|
+
|
|
438
|
+
if cls.regex:
|
|
439
|
+
if not re.match(cls.regex, value):
|
|
440
|
+
raise errors.StrRegexError(pattern=cls._get_pattern(cls.regex))
|
|
441
|
+
|
|
442
|
+
return value
|
|
443
|
+
|
|
444
|
+
@staticmethod
|
|
445
|
+
def _get_pattern(regex: Union[str, Pattern[str]]) -> str:
|
|
446
|
+
return regex if isinstance(regex, str) else regex.pattern
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def constr(
|
|
450
|
+
*,
|
|
451
|
+
strip_whitespace: bool = False,
|
|
452
|
+
to_upper: bool = False,
|
|
453
|
+
to_lower: bool = False,
|
|
454
|
+
strict: bool = False,
|
|
455
|
+
min_length: Optional[int] = None,
|
|
456
|
+
max_length: Optional[int] = None,
|
|
457
|
+
curtail_length: Optional[int] = None,
|
|
458
|
+
regex: Optional[str] = None,
|
|
459
|
+
) -> Type[str]:
|
|
460
|
+
# use kwargs then define conf in a dict to aid with IDE type hinting
|
|
461
|
+
namespace = dict(
|
|
462
|
+
strip_whitespace=strip_whitespace,
|
|
463
|
+
to_upper=to_upper,
|
|
464
|
+
to_lower=to_lower,
|
|
465
|
+
strict=strict,
|
|
466
|
+
min_length=min_length,
|
|
467
|
+
max_length=max_length,
|
|
468
|
+
curtail_length=curtail_length,
|
|
469
|
+
regex=regex and re.compile(regex),
|
|
470
|
+
)
|
|
471
|
+
return _registered(type('ConstrainedStrValue', (ConstrainedStr,), namespace))
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
if TYPE_CHECKING:
|
|
475
|
+
StrictStr = str
|
|
476
|
+
else:
|
|
477
|
+
|
|
478
|
+
class StrictStr(ConstrainedStr):
|
|
479
|
+
strict = True
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SET TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
# This types superclass should be Set[T], but cython chokes on that...
|
|
486
|
+
class ConstrainedSet(set): # type: ignore
|
|
487
|
+
# Needed for pydantic to detect that this is a set
|
|
488
|
+
__origin__ = set
|
|
489
|
+
__args__: Set[Type[T]] # type: ignore
|
|
490
|
+
|
|
491
|
+
min_items: Optional[int] = None
|
|
492
|
+
max_items: Optional[int] = None
|
|
493
|
+
item_type: Type[T] # type: ignore
|
|
494
|
+
|
|
495
|
+
@classmethod
|
|
496
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
497
|
+
yield cls.set_length_validator
|
|
498
|
+
|
|
499
|
+
@classmethod
|
|
500
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
501
|
+
update_not_none(field_schema, minItems=cls.min_items, maxItems=cls.max_items)
|
|
502
|
+
|
|
503
|
+
@classmethod
|
|
504
|
+
def set_length_validator(cls, v: 'Optional[Set[T]]') -> 'Optional[Set[T]]':
|
|
505
|
+
if v is None:
|
|
506
|
+
return None
|
|
507
|
+
|
|
508
|
+
v = set_validator(v)
|
|
509
|
+
v_len = len(v)
|
|
510
|
+
|
|
511
|
+
if cls.min_items is not None and v_len < cls.min_items:
|
|
512
|
+
raise errors.SetMinLengthError(limit_value=cls.min_items)
|
|
513
|
+
|
|
514
|
+
if cls.max_items is not None and v_len > cls.max_items:
|
|
515
|
+
raise errors.SetMaxLengthError(limit_value=cls.max_items)
|
|
516
|
+
|
|
517
|
+
return v
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def conset(item_type: Type[T], *, min_items: Optional[int] = None, max_items: Optional[int] = None) -> Type[Set[T]]:
|
|
521
|
+
# __args__ is needed to conform to typing generics api
|
|
522
|
+
namespace = {'min_items': min_items, 'max_items': max_items, 'item_type': item_type, '__args__': [item_type]}
|
|
523
|
+
# We use new_class to be able to deal with Generic types
|
|
524
|
+
return new_class('ConstrainedSetValue', (ConstrainedSet,), {}, lambda ns: ns.update(namespace))
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
# This types superclass should be FrozenSet[T], but cython chokes on that...
|
|
528
|
+
class ConstrainedFrozenSet(frozenset): # type: ignore
|
|
529
|
+
# Needed for pydantic to detect that this is a set
|
|
530
|
+
__origin__ = frozenset
|
|
531
|
+
__args__: FrozenSet[Type[T]] # type: ignore
|
|
532
|
+
|
|
533
|
+
min_items: Optional[int] = None
|
|
534
|
+
max_items: Optional[int] = None
|
|
535
|
+
item_type: Type[T] # type: ignore
|
|
536
|
+
|
|
537
|
+
@classmethod
|
|
538
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
539
|
+
yield cls.frozenset_length_validator
|
|
540
|
+
|
|
541
|
+
@classmethod
|
|
542
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
543
|
+
update_not_none(field_schema, minItems=cls.min_items, maxItems=cls.max_items)
|
|
544
|
+
|
|
545
|
+
@classmethod
|
|
546
|
+
def frozenset_length_validator(cls, v: 'Optional[FrozenSet[T]]') -> 'Optional[FrozenSet[T]]':
|
|
547
|
+
if v is None:
|
|
548
|
+
return None
|
|
549
|
+
|
|
550
|
+
v = frozenset_validator(v)
|
|
551
|
+
v_len = len(v)
|
|
552
|
+
|
|
553
|
+
if cls.min_items is not None and v_len < cls.min_items:
|
|
554
|
+
raise errors.FrozenSetMinLengthError(limit_value=cls.min_items)
|
|
555
|
+
|
|
556
|
+
if cls.max_items is not None and v_len > cls.max_items:
|
|
557
|
+
raise errors.FrozenSetMaxLengthError(limit_value=cls.max_items)
|
|
558
|
+
|
|
559
|
+
return v
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def confrozenset(
|
|
563
|
+
item_type: Type[T], *, min_items: Optional[int] = None, max_items: Optional[int] = None
|
|
564
|
+
) -> Type[FrozenSet[T]]:
|
|
565
|
+
# __args__ is needed to conform to typing generics api
|
|
566
|
+
namespace = {'min_items': min_items, 'max_items': max_items, 'item_type': item_type, '__args__': [item_type]}
|
|
567
|
+
# We use new_class to be able to deal with Generic types
|
|
568
|
+
return new_class('ConstrainedFrozenSetValue', (ConstrainedFrozenSet,), {}, lambda ns: ns.update(namespace))
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LIST TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
# This types superclass should be List[T], but cython chokes on that...
|
|
575
|
+
_HASHABLE_SCALAR_TYPES = {int, float, str, bytes, bool, type(None)}
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
class ConstrainedList(list): # type: ignore
|
|
579
|
+
# Needed for pydantic to detect that this is a list
|
|
580
|
+
__origin__ = list
|
|
581
|
+
__args__: Tuple[Type[T], ...] # type: ignore
|
|
582
|
+
|
|
583
|
+
min_items: Optional[int] = None
|
|
584
|
+
max_items: Optional[int] = None
|
|
585
|
+
unique_items: Optional[bool] = None
|
|
586
|
+
item_type: Type[T] # type: ignore
|
|
587
|
+
|
|
588
|
+
@classmethod
|
|
589
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
590
|
+
yield cls.list_length_validator
|
|
591
|
+
if cls.unique_items:
|
|
592
|
+
yield cls.unique_items_validator
|
|
593
|
+
|
|
594
|
+
@classmethod
|
|
595
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
596
|
+
update_not_none(field_schema, minItems=cls.min_items, maxItems=cls.max_items, uniqueItems=cls.unique_items)
|
|
597
|
+
|
|
598
|
+
@classmethod
|
|
599
|
+
def list_length_validator(cls, v: 'Optional[List[T]]') -> 'Optional[List[T]]':
|
|
600
|
+
if v is None:
|
|
601
|
+
return None
|
|
602
|
+
|
|
603
|
+
v = list_validator(v)
|
|
604
|
+
v_len = len(v)
|
|
605
|
+
|
|
606
|
+
if cls.min_items is not None and v_len < cls.min_items:
|
|
607
|
+
raise errors.ListMinLengthError(limit_value=cls.min_items)
|
|
608
|
+
|
|
609
|
+
if cls.max_items is not None and v_len > cls.max_items:
|
|
610
|
+
raise errors.ListMaxLengthError(limit_value=cls.max_items)
|
|
611
|
+
|
|
612
|
+
return v
|
|
613
|
+
|
|
614
|
+
@classmethod
|
|
615
|
+
def unique_items_validator(cls, v: 'Optional[List[T]]') -> 'Optional[List[T]]':
|
|
616
|
+
if v is None:
|
|
617
|
+
return None
|
|
618
|
+
|
|
619
|
+
if all(type(value) in _HASHABLE_SCALAR_TYPES for value in v):
|
|
620
|
+
# builtin scalars have well-behaved hashing, duplicates can be detected in linear time:
|
|
621
|
+
has_duplicates = len(set(v)) != len(v)
|
|
622
|
+
else:
|
|
623
|
+
has_duplicates = any(value in v[i:] for i, value in enumerate(v, start=1))
|
|
624
|
+
|
|
625
|
+
if has_duplicates:
|
|
626
|
+
raise errors.ListUniqueItemsError()
|
|
627
|
+
|
|
628
|
+
return v
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def conlist(
|
|
632
|
+
item_type: Type[T], *, min_items: Optional[int] = None, max_items: Optional[int] = None, unique_items: bool = None
|
|
633
|
+
) -> Type[List[T]]:
|
|
634
|
+
# __args__ is needed to conform to typing generics api
|
|
635
|
+
namespace = dict(
|
|
636
|
+
min_items=min_items, max_items=max_items, unique_items=unique_items, item_type=item_type, __args__=(item_type,)
|
|
637
|
+
)
|
|
638
|
+
# We use new_class to be able to deal with Generic types
|
|
639
|
+
return new_class('ConstrainedListValue', (ConstrainedList,), {}, lambda ns: ns.update(namespace))
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PYOBJECT TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
if TYPE_CHECKING:
|
|
646
|
+
PyObject = Callable[..., Any]
|
|
647
|
+
else:
|
|
648
|
+
|
|
649
|
+
class PyObject:
|
|
650
|
+
validate_always = True
|
|
651
|
+
|
|
652
|
+
@classmethod
|
|
653
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
654
|
+
yield cls.validate
|
|
655
|
+
|
|
656
|
+
@classmethod
|
|
657
|
+
def validate(cls, value: Any) -> Any:
|
|
658
|
+
if isinstance(value, Callable):
|
|
659
|
+
return value
|
|
660
|
+
|
|
661
|
+
try:
|
|
662
|
+
value = str_validator(value)
|
|
663
|
+
except errors.StrError:
|
|
664
|
+
raise errors.PyObjectError(error_message='value is neither a valid import path not a valid callable')
|
|
665
|
+
|
|
666
|
+
try:
|
|
667
|
+
return import_string(value)
|
|
668
|
+
except ImportError as e:
|
|
669
|
+
raise errors.PyObjectError(error_message=str(e))
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DECIMAL TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
class ConstrainedDecimal(Decimal, metaclass=ConstrainedNumberMeta):
|
|
676
|
+
gt: OptionalIntFloatDecimal = None
|
|
677
|
+
ge: OptionalIntFloatDecimal = None
|
|
678
|
+
lt: OptionalIntFloatDecimal = None
|
|
679
|
+
le: OptionalIntFloatDecimal = None
|
|
680
|
+
max_digits: OptionalInt = None
|
|
681
|
+
decimal_places: OptionalInt = None
|
|
682
|
+
multiple_of: OptionalIntFloatDecimal = None
|
|
683
|
+
|
|
684
|
+
@classmethod
|
|
685
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
686
|
+
update_not_none(
|
|
687
|
+
field_schema,
|
|
688
|
+
exclusiveMinimum=cls.gt,
|
|
689
|
+
exclusiveMaximum=cls.lt,
|
|
690
|
+
minimum=cls.ge,
|
|
691
|
+
maximum=cls.le,
|
|
692
|
+
multipleOf=cls.multiple_of,
|
|
693
|
+
)
|
|
694
|
+
|
|
695
|
+
@classmethod
|
|
696
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
697
|
+
yield decimal_validator
|
|
698
|
+
yield number_size_validator
|
|
699
|
+
yield number_multiple_validator
|
|
700
|
+
yield cls.validate
|
|
701
|
+
|
|
702
|
+
@classmethod
|
|
703
|
+
def validate(cls, value: Decimal) -> Decimal:
|
|
704
|
+
try:
|
|
705
|
+
normalized_value = value.normalize()
|
|
706
|
+
except InvalidOperation:
|
|
707
|
+
normalized_value = value
|
|
708
|
+
digit_tuple, exponent = normalized_value.as_tuple()[1:]
|
|
709
|
+
if exponent in {'F', 'n', 'N'}:
|
|
710
|
+
raise errors.DecimalIsNotFiniteError()
|
|
711
|
+
|
|
712
|
+
if exponent >= 0:
|
|
713
|
+
# A positive exponent adds that many trailing zeros.
|
|
714
|
+
digits = len(digit_tuple) + exponent
|
|
715
|
+
decimals = 0
|
|
716
|
+
else:
|
|
717
|
+
# If the absolute value of the negative exponent is larger than the
|
|
718
|
+
# number of digits, then it's the same as the number of digits,
|
|
719
|
+
# because it'll consume all of the digits in digit_tuple and then
|
|
720
|
+
# add abs(exponent) - len(digit_tuple) leading zeros after the
|
|
721
|
+
# decimal point.
|
|
722
|
+
if abs(exponent) > len(digit_tuple):
|
|
723
|
+
digits = decimals = abs(exponent)
|
|
724
|
+
else:
|
|
725
|
+
digits = len(digit_tuple)
|
|
726
|
+
decimals = abs(exponent)
|
|
727
|
+
whole_digits = digits - decimals
|
|
728
|
+
|
|
729
|
+
if cls.max_digits is not None and digits > cls.max_digits:
|
|
730
|
+
raise errors.DecimalMaxDigitsError(max_digits=cls.max_digits)
|
|
731
|
+
|
|
732
|
+
if cls.decimal_places is not None and decimals > cls.decimal_places:
|
|
733
|
+
raise errors.DecimalMaxPlacesError(decimal_places=cls.decimal_places)
|
|
734
|
+
|
|
735
|
+
if cls.max_digits is not None and cls.decimal_places is not None:
|
|
736
|
+
expected = cls.max_digits - cls.decimal_places
|
|
737
|
+
if whole_digits > expected:
|
|
738
|
+
raise errors.DecimalWholeDigitsError(whole_digits=expected)
|
|
739
|
+
|
|
740
|
+
return value
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def condecimal(
|
|
744
|
+
*,
|
|
745
|
+
gt: Decimal = None,
|
|
746
|
+
ge: Decimal = None,
|
|
747
|
+
lt: Decimal = None,
|
|
748
|
+
le: Decimal = None,
|
|
749
|
+
max_digits: Optional[int] = None,
|
|
750
|
+
decimal_places: Optional[int] = None,
|
|
751
|
+
multiple_of: Decimal = None,
|
|
752
|
+
) -> Type[Decimal]:
|
|
753
|
+
# use kwargs then define conf in a dict to aid with IDE type hinting
|
|
754
|
+
namespace = dict(
|
|
755
|
+
gt=gt, ge=ge, lt=lt, le=le, max_digits=max_digits, decimal_places=decimal_places, multiple_of=multiple_of
|
|
756
|
+
)
|
|
757
|
+
return type('ConstrainedDecimalValue', (ConstrainedDecimal,), namespace)
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ UUID TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
761
|
+
|
|
762
|
+
if TYPE_CHECKING:
|
|
763
|
+
UUID1 = UUID
|
|
764
|
+
UUID3 = UUID
|
|
765
|
+
UUID4 = UUID
|
|
766
|
+
UUID5 = UUID
|
|
767
|
+
else:
|
|
768
|
+
|
|
769
|
+
class UUID1(UUID):
|
|
770
|
+
_required_version = 1
|
|
771
|
+
|
|
772
|
+
@classmethod
|
|
773
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
774
|
+
field_schema.update(type='string', format=f'uuid{cls._required_version}')
|
|
775
|
+
|
|
776
|
+
class UUID3(UUID1):
|
|
777
|
+
_required_version = 3
|
|
778
|
+
|
|
779
|
+
class UUID4(UUID1):
|
|
780
|
+
_required_version = 4
|
|
781
|
+
|
|
782
|
+
class UUID5(UUID1):
|
|
783
|
+
_required_version = 5
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PATH TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
787
|
+
|
|
788
|
+
if TYPE_CHECKING:
|
|
789
|
+
FilePath = Path
|
|
790
|
+
DirectoryPath = Path
|
|
791
|
+
else:
|
|
792
|
+
|
|
793
|
+
class FilePath(Path):
|
|
794
|
+
@classmethod
|
|
795
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
796
|
+
field_schema.update(format='file-path')
|
|
797
|
+
|
|
798
|
+
@classmethod
|
|
799
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
800
|
+
yield path_validator
|
|
801
|
+
yield path_exists_validator
|
|
802
|
+
yield cls.validate
|
|
803
|
+
|
|
804
|
+
@classmethod
|
|
805
|
+
def validate(cls, value: Path) -> Path:
|
|
806
|
+
if not value.is_file():
|
|
807
|
+
raise errors.PathNotAFileError(path=value)
|
|
808
|
+
|
|
809
|
+
return value
|
|
810
|
+
|
|
811
|
+
class DirectoryPath(Path):
|
|
812
|
+
@classmethod
|
|
813
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
814
|
+
field_schema.update(format='directory-path')
|
|
815
|
+
|
|
816
|
+
@classmethod
|
|
817
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
818
|
+
yield path_validator
|
|
819
|
+
yield path_exists_validator
|
|
820
|
+
yield cls.validate
|
|
821
|
+
|
|
822
|
+
@classmethod
|
|
823
|
+
def validate(cls, value: Path) -> Path:
|
|
824
|
+
if not value.is_dir():
|
|
825
|
+
raise errors.PathNotADirectoryError(path=value)
|
|
826
|
+
|
|
827
|
+
return value
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ JSON TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
class JsonWrapper:
|
|
834
|
+
pass
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
class JsonMeta(type):
|
|
838
|
+
def __getitem__(self, t: Type[Any]) -> Type[JsonWrapper]:
|
|
839
|
+
if t is Any:
|
|
840
|
+
return Json # allow Json[Any] to replicate plain Json
|
|
841
|
+
return _registered(type('JsonWrapperValue', (JsonWrapper,), {'inner_type': t}))
|
|
842
|
+
|
|
843
|
+
|
|
844
|
+
if TYPE_CHECKING:
|
|
845
|
+
Json = Annotated[T, ...] # Json[list[str]] will be recognized by type checkers as list[str]
|
|
846
|
+
|
|
847
|
+
else:
|
|
848
|
+
|
|
849
|
+
class Json(metaclass=JsonMeta):
|
|
850
|
+
@classmethod
|
|
851
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
852
|
+
field_schema.update(type='string', format='json-string')
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SECRET TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
class SecretField(abc.ABC):
|
|
859
|
+
"""
|
|
860
|
+
Note: this should be implemented as a generic like `SecretField(ABC, Generic[T])`,
|
|
861
|
+
the `__init__()` should be part of the abstract class and the
|
|
862
|
+
`get_secret_value()` method should use the generic `T` type.
|
|
863
|
+
|
|
864
|
+
However Cython doesn't support very well generics at the moment and
|
|
865
|
+
the generated code fails to be imported (see
|
|
866
|
+
https://github.com/cython/cython/issues/2753).
|
|
867
|
+
"""
|
|
868
|
+
|
|
869
|
+
def __eq__(self, other: Any) -> bool:
|
|
870
|
+
return isinstance(other, self.__class__) and self.get_secret_value() == other.get_secret_value()
|
|
871
|
+
|
|
872
|
+
def __str__(self) -> str:
|
|
873
|
+
return '**********' if self.get_secret_value() else ''
|
|
874
|
+
|
|
875
|
+
def __hash__(self) -> int:
|
|
876
|
+
return hash(self.get_secret_value())
|
|
877
|
+
|
|
878
|
+
@abc.abstractmethod
|
|
879
|
+
def get_secret_value(self) -> Any: # pragma: no cover
|
|
880
|
+
...
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
class SecretStr(SecretField):
|
|
884
|
+
min_length: OptionalInt = None
|
|
885
|
+
max_length: OptionalInt = None
|
|
886
|
+
|
|
887
|
+
@classmethod
|
|
888
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
889
|
+
update_not_none(
|
|
890
|
+
field_schema,
|
|
891
|
+
type='string',
|
|
892
|
+
writeOnly=True,
|
|
893
|
+
format='password',
|
|
894
|
+
minLength=cls.min_length,
|
|
895
|
+
maxLength=cls.max_length,
|
|
896
|
+
)
|
|
897
|
+
|
|
898
|
+
@classmethod
|
|
899
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
900
|
+
yield cls.validate
|
|
901
|
+
yield constr_length_validator
|
|
902
|
+
|
|
903
|
+
@classmethod
|
|
904
|
+
def validate(cls, value: Any) -> 'SecretStr':
|
|
905
|
+
if isinstance(value, cls):
|
|
906
|
+
return value
|
|
907
|
+
value = str_validator(value)
|
|
908
|
+
return cls(value)
|
|
909
|
+
|
|
910
|
+
def __init__(self, value: str):
|
|
911
|
+
self._secret_value = value
|
|
912
|
+
|
|
913
|
+
def __repr__(self) -> str:
|
|
914
|
+
return f"SecretStr('{self}')"
|
|
915
|
+
|
|
916
|
+
def __len__(self) -> int:
|
|
917
|
+
return len(self._secret_value)
|
|
918
|
+
|
|
919
|
+
def display(self) -> str:
|
|
920
|
+
warnings.warn('`secret_str.display()` is deprecated, use `str(secret_str)` instead', DeprecationWarning)
|
|
921
|
+
return str(self)
|
|
922
|
+
|
|
923
|
+
def get_secret_value(self) -> str:
|
|
924
|
+
return self._secret_value
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
class SecretBytes(SecretField):
|
|
928
|
+
min_length: OptionalInt = None
|
|
929
|
+
max_length: OptionalInt = None
|
|
930
|
+
|
|
931
|
+
@classmethod
|
|
932
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
933
|
+
update_not_none(
|
|
934
|
+
field_schema,
|
|
935
|
+
type='string',
|
|
936
|
+
writeOnly=True,
|
|
937
|
+
format='password',
|
|
938
|
+
minLength=cls.min_length,
|
|
939
|
+
maxLength=cls.max_length,
|
|
940
|
+
)
|
|
941
|
+
|
|
942
|
+
@classmethod
|
|
943
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
944
|
+
yield cls.validate
|
|
945
|
+
yield constr_length_validator
|
|
946
|
+
|
|
947
|
+
@classmethod
|
|
948
|
+
def validate(cls, value: Any) -> 'SecretBytes':
|
|
949
|
+
if isinstance(value, cls):
|
|
950
|
+
return value
|
|
951
|
+
value = bytes_validator(value)
|
|
952
|
+
return cls(value)
|
|
953
|
+
|
|
954
|
+
def __init__(self, value: bytes):
|
|
955
|
+
self._secret_value = value
|
|
956
|
+
|
|
957
|
+
def __repr__(self) -> str:
|
|
958
|
+
return f"SecretBytes(b'{self}')"
|
|
959
|
+
|
|
960
|
+
def __len__(self) -> int:
|
|
961
|
+
return len(self._secret_value)
|
|
962
|
+
|
|
963
|
+
def display(self) -> str:
|
|
964
|
+
warnings.warn('`secret_bytes.display()` is deprecated, use `str(secret_bytes)` instead', DeprecationWarning)
|
|
965
|
+
return str(self)
|
|
966
|
+
|
|
967
|
+
def get_secret_value(self) -> bytes:
|
|
968
|
+
return self._secret_value
|
|
969
|
+
|
|
970
|
+
|
|
971
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PAYMENT CARD TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
972
|
+
|
|
973
|
+
|
|
974
|
+
class PaymentCardBrand(str, Enum):
|
|
975
|
+
# If you add another card type, please also add it to the
|
|
976
|
+
# Hypothesis strategy in `pboot_validator._hypothesis_plugin`.
|
|
977
|
+
amex = 'American Express'
|
|
978
|
+
mastercard = 'Mastercard'
|
|
979
|
+
visa = 'Visa'
|
|
980
|
+
other = 'other'
|
|
981
|
+
|
|
982
|
+
def __str__(self) -> str:
|
|
983
|
+
return self.value
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
class PaymentCardNumber(str):
|
|
987
|
+
"""
|
|
988
|
+
Based on: https://en.wikipedia.org/wiki/Payment_card_number
|
|
989
|
+
"""
|
|
990
|
+
|
|
991
|
+
strip_whitespace: ClassVar[bool] = True
|
|
992
|
+
min_length: ClassVar[int] = 12
|
|
993
|
+
max_length: ClassVar[int] = 19
|
|
994
|
+
bin: str
|
|
995
|
+
last4: str
|
|
996
|
+
brand: PaymentCardBrand
|
|
997
|
+
|
|
998
|
+
def __init__(self, card_number: str):
|
|
999
|
+
self.bin = card_number[:6]
|
|
1000
|
+
self.last4 = card_number[-4:]
|
|
1001
|
+
self.brand = self._get_brand(card_number)
|
|
1002
|
+
|
|
1003
|
+
@classmethod
|
|
1004
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
1005
|
+
yield str_validator
|
|
1006
|
+
yield constr_strip_whitespace
|
|
1007
|
+
yield constr_length_validator
|
|
1008
|
+
yield cls.validate_digits
|
|
1009
|
+
yield cls.validate_luhn_check_digit
|
|
1010
|
+
yield cls
|
|
1011
|
+
yield cls.validate_length_for_brand
|
|
1012
|
+
|
|
1013
|
+
@property
|
|
1014
|
+
def masked(self) -> str:
|
|
1015
|
+
num_masked = len(self) - 10 # len(bin) + len(last4) == 10
|
|
1016
|
+
return f'{self.bin}{"*" * num_masked}{self.last4}'
|
|
1017
|
+
|
|
1018
|
+
@classmethod
|
|
1019
|
+
def validate_digits(cls, card_number: str) -> str:
|
|
1020
|
+
if not card_number.isdigit():
|
|
1021
|
+
raise errors.NotDigitError
|
|
1022
|
+
return card_number
|
|
1023
|
+
|
|
1024
|
+
@classmethod
|
|
1025
|
+
def validate_luhn_check_digit(cls, card_number: str) -> str:
|
|
1026
|
+
"""
|
|
1027
|
+
Based on: https://en.wikipedia.org/wiki/Luhn_algorithm
|
|
1028
|
+
"""
|
|
1029
|
+
sum_ = int(card_number[-1])
|
|
1030
|
+
length = len(card_number)
|
|
1031
|
+
parity = length % 2
|
|
1032
|
+
for i in range(length - 1):
|
|
1033
|
+
digit = int(card_number[i])
|
|
1034
|
+
if i % 2 == parity:
|
|
1035
|
+
digit *= 2
|
|
1036
|
+
if digit > 9:
|
|
1037
|
+
digit -= 9
|
|
1038
|
+
sum_ += digit
|
|
1039
|
+
valid = sum_ % 10 == 0
|
|
1040
|
+
if not valid:
|
|
1041
|
+
raise errors.LuhnValidationError
|
|
1042
|
+
return card_number
|
|
1043
|
+
|
|
1044
|
+
@classmethod
|
|
1045
|
+
def validate_length_for_brand(cls, card_number: 'PaymentCardNumber') -> 'PaymentCardNumber':
|
|
1046
|
+
"""
|
|
1047
|
+
Validate length based on BIN for major brands:
|
|
1048
|
+
https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN)
|
|
1049
|
+
"""
|
|
1050
|
+
required_length: Union[None, int, str] = None
|
|
1051
|
+
if card_number.brand in PaymentCardBrand.mastercard:
|
|
1052
|
+
required_length = 16
|
|
1053
|
+
valid = len(card_number) == required_length
|
|
1054
|
+
elif card_number.brand == PaymentCardBrand.visa:
|
|
1055
|
+
required_length = '13, 16 or 19'
|
|
1056
|
+
valid = len(card_number) in {13, 16, 19}
|
|
1057
|
+
elif card_number.brand == PaymentCardBrand.amex:
|
|
1058
|
+
required_length = 15
|
|
1059
|
+
valid = len(card_number) == required_length
|
|
1060
|
+
else:
|
|
1061
|
+
valid = True
|
|
1062
|
+
if not valid:
|
|
1063
|
+
raise errors.InvalidLengthForBrand(brand=card_number.brand, required_length=required_length)
|
|
1064
|
+
return card_number
|
|
1065
|
+
|
|
1066
|
+
@staticmethod
|
|
1067
|
+
def _get_brand(card_number: str) -> PaymentCardBrand:
|
|
1068
|
+
if card_number[0] == '4':
|
|
1069
|
+
brand = PaymentCardBrand.visa
|
|
1070
|
+
elif 51 <= int(card_number[:2]) <= 55:
|
|
1071
|
+
brand = PaymentCardBrand.mastercard
|
|
1072
|
+
elif card_number[:2] in {'34', '37'}:
|
|
1073
|
+
brand = PaymentCardBrand.amex
|
|
1074
|
+
else:
|
|
1075
|
+
brand = PaymentCardBrand.other
|
|
1076
|
+
return brand
|
|
1077
|
+
|
|
1078
|
+
|
|
1079
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BYTE SIZE TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
1080
|
+
|
|
1081
|
+
BYTE_SIZES = {
|
|
1082
|
+
'b': 1,
|
|
1083
|
+
'kb': 10**3,
|
|
1084
|
+
'mb': 10**6,
|
|
1085
|
+
'gb': 10**9,
|
|
1086
|
+
'tb': 10**12,
|
|
1087
|
+
'pb': 10**15,
|
|
1088
|
+
'eb': 10**18,
|
|
1089
|
+
'kib': 2**10,
|
|
1090
|
+
'mib': 2**20,
|
|
1091
|
+
'gib': 2**30,
|
|
1092
|
+
'tib': 2**40,
|
|
1093
|
+
'pib': 2**50,
|
|
1094
|
+
'eib': 2**60,
|
|
1095
|
+
}
|
|
1096
|
+
BYTE_SIZES.update({k.lower()[0]: v for k, v in BYTE_SIZES.items() if 'i' not in k})
|
|
1097
|
+
byte_string_re = re.compile(r'^\s*(\d*\.?\d+)\s*(\w+)?', re.IGNORECASE)
|
|
1098
|
+
|
|
1099
|
+
|
|
1100
|
+
class ByteSize(int):
|
|
1101
|
+
@classmethod
|
|
1102
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
1103
|
+
yield cls.validate
|
|
1104
|
+
|
|
1105
|
+
@classmethod
|
|
1106
|
+
def validate(cls, v: StrIntFloat) -> 'ByteSize':
|
|
1107
|
+
try:
|
|
1108
|
+
return cls(int(v))
|
|
1109
|
+
except ValueError:
|
|
1110
|
+
pass
|
|
1111
|
+
|
|
1112
|
+
str_match = byte_string_re.match(str(v))
|
|
1113
|
+
if str_match is None:
|
|
1114
|
+
raise errors.InvalidByteSize()
|
|
1115
|
+
|
|
1116
|
+
scalar, unit = str_match.groups()
|
|
1117
|
+
if unit is None:
|
|
1118
|
+
unit = 'b'
|
|
1119
|
+
|
|
1120
|
+
try:
|
|
1121
|
+
unit_mult = BYTE_SIZES[unit.lower()]
|
|
1122
|
+
except KeyError:
|
|
1123
|
+
raise errors.InvalidByteSizeUnit(unit=unit)
|
|
1124
|
+
|
|
1125
|
+
return cls(int(float(scalar) * unit_mult))
|
|
1126
|
+
|
|
1127
|
+
def human_readable(self, decimal: bool = False) -> str:
|
|
1128
|
+
if decimal:
|
|
1129
|
+
divisor = 1000
|
|
1130
|
+
units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
|
|
1131
|
+
final_unit = 'EB'
|
|
1132
|
+
else:
|
|
1133
|
+
divisor = 1024
|
|
1134
|
+
units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']
|
|
1135
|
+
final_unit = 'EiB'
|
|
1136
|
+
|
|
1137
|
+
num = float(self)
|
|
1138
|
+
for unit in units:
|
|
1139
|
+
if abs(num) < divisor:
|
|
1140
|
+
return f'{num:0.1f}{unit}'
|
|
1141
|
+
num /= divisor
|
|
1142
|
+
|
|
1143
|
+
return f'{num:0.1f}{final_unit}'
|
|
1144
|
+
|
|
1145
|
+
def to(self, unit: str) -> float:
|
|
1146
|
+
try:
|
|
1147
|
+
unit_div = BYTE_SIZES[unit.lower()]
|
|
1148
|
+
except KeyError:
|
|
1149
|
+
raise errors.InvalidByteSizeUnit(unit=unit)
|
|
1150
|
+
|
|
1151
|
+
return self / unit_div
|
|
1152
|
+
|
|
1153
|
+
|
|
1154
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DATE TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
1155
|
+
|
|
1156
|
+
if TYPE_CHECKING:
|
|
1157
|
+
PastDate = date
|
|
1158
|
+
FutureDate = date
|
|
1159
|
+
else:
|
|
1160
|
+
|
|
1161
|
+
class PastDate(date):
|
|
1162
|
+
@classmethod
|
|
1163
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
1164
|
+
yield parse_date
|
|
1165
|
+
yield cls.validate
|
|
1166
|
+
|
|
1167
|
+
@classmethod
|
|
1168
|
+
def validate(cls, value: date) -> date:
|
|
1169
|
+
if value >= date.today():
|
|
1170
|
+
raise errors.DateNotInThePastError()
|
|
1171
|
+
|
|
1172
|
+
return value
|
|
1173
|
+
|
|
1174
|
+
class FutureDate(date):
|
|
1175
|
+
@classmethod
|
|
1176
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
1177
|
+
yield parse_date
|
|
1178
|
+
yield cls.validate
|
|
1179
|
+
|
|
1180
|
+
@classmethod
|
|
1181
|
+
def validate(cls, value: date) -> date:
|
|
1182
|
+
if value <= date.today():
|
|
1183
|
+
raise errors.DateNotInTheFutureError()
|
|
1184
|
+
|
|
1185
|
+
return value
|
|
1186
|
+
|
|
1187
|
+
|
|
1188
|
+
class ConstrainedDate(date, metaclass=ConstrainedNumberMeta):
|
|
1189
|
+
gt: OptionalDate = None
|
|
1190
|
+
ge: OptionalDate = None
|
|
1191
|
+
lt: OptionalDate = None
|
|
1192
|
+
le: OptionalDate = None
|
|
1193
|
+
|
|
1194
|
+
@classmethod
|
|
1195
|
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
|
1196
|
+
update_not_none(field_schema, exclusiveMinimum=cls.gt, exclusiveMaximum=cls.lt, minimum=cls.ge, maximum=cls.le)
|
|
1197
|
+
|
|
1198
|
+
@classmethod
|
|
1199
|
+
def __get_validators__(cls) -> 'CallableGenerator':
|
|
1200
|
+
yield parse_date
|
|
1201
|
+
yield number_size_validator
|
|
1202
|
+
|
|
1203
|
+
|
|
1204
|
+
def condate(
|
|
1205
|
+
*,
|
|
1206
|
+
gt: date = None,
|
|
1207
|
+
ge: date = None,
|
|
1208
|
+
lt: date = None,
|
|
1209
|
+
le: date = None,
|
|
1210
|
+
) -> Type[date]:
|
|
1211
|
+
# use kwargs then define conf in a dict to aid with IDE type hinting
|
|
1212
|
+
namespace = dict(gt=gt, ge=ge, lt=lt, le=le)
|
|
1213
|
+
return type('ConstrainedDateValue', (ConstrainedDate,), namespace)
|