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.
Files changed (112) hide show
  1. pboot_validator/__init__.py +461 -0
  2. pboot_validator/_internal/__init__.py +0 -0
  3. pboot_validator/_internal/_config.py +408 -0
  4. pboot_validator/_internal/_contextlib.py +84 -0
  5. pboot_validator/_internal/_core_metadata.py +97 -0
  6. pboot_validator/_internal/_core_utils.py +156 -0
  7. pboot_validator/_internal/_dataclasses.py +327 -0
  8. pboot_validator/_internal/_decorators.py +906 -0
  9. pboot_validator/_internal/_decorators_v1.py +174 -0
  10. pboot_validator/_internal/_discriminated_union.py +510 -0
  11. pboot_validator/_internal/_docs_extraction.py +128 -0
  12. pboot_validator/_internal/_fields.py +910 -0
  13. pboot_validator/_internal/_forward_ref.py +23 -0
  14. pboot_validator/_internal/_generate_schema.py +3053 -0
  15. pboot_validator/_internal/_generics.py +572 -0
  16. pboot_validator/_internal/_git.py +27 -0
  17. pboot_validator/_internal/_import_utils.py +20 -0
  18. pboot_validator/_internal/_known_annotated_metadata.py +412 -0
  19. pboot_validator/_internal/_mock_val_ser.py +241 -0
  20. pboot_validator/_internal/_model_construction.py +833 -0
  21. pboot_validator/_internal/_namespace_utils.py +300 -0
  22. pboot_validator/_internal/_repr.py +129 -0
  23. pboot_validator/_internal/_schema_gather.py +49 -0
  24. pboot_validator/_internal/_schema_generation_shared.py +126 -0
  25. pboot_validator/_internal/_serializers.py +59 -0
  26. pboot_validator/_internal/_signature.py +193 -0
  27. pboot_validator/_internal/_type_refs.py +128 -0
  28. pboot_validator/_internal/_typing_extra.py +506 -0
  29. pboot_validator/_internal/_utils.py +433 -0
  30. pboot_validator/_internal/_validate_call.py +141 -0
  31. pboot_validator/_internal/_validators.py +541 -0
  32. pboot_validator/_migration.py +317 -0
  33. pboot_validator/alias_generators.py +62 -0
  34. pboot_validator/aliases.py +136 -0
  35. pboot_validator/annotated_handlers.py +123 -0
  36. pboot_validator/class_validators.py +5 -0
  37. pboot_validator/color.py +605 -0
  38. pboot_validator/config.py +1295 -0
  39. pboot_validator/dataclasses.py +385 -0
  40. pboot_validator/datetime_parse.py +5 -0
  41. pboot_validator/decorator.py +5 -0
  42. pboot_validator/deprecated/__init__.py +0 -0
  43. pboot_validator/deprecated/class_validators.py +257 -0
  44. pboot_validator/deprecated/config.py +72 -0
  45. pboot_validator/deprecated/copy_internals.py +224 -0
  46. pboot_validator/deprecated/decorator.py +286 -0
  47. pboot_validator/deprecated/json.py +142 -0
  48. pboot_validator/deprecated/parse.py +81 -0
  49. pboot_validator/deprecated/tools.py +104 -0
  50. pboot_validator/env_settings.py +5 -0
  51. pboot_validator/error_wrappers.py +5 -0
  52. pboot_validator/errors.py +185 -0
  53. pboot_validator/experimental/__init__.py +1 -0
  54. pboot_validator/experimental/arguments_schema.py +44 -0
  55. pboot_validator/experimental/missing_sentinel.py +29 -0
  56. pboot_validator/experimental/pipeline.py +684 -0
  57. pboot_validator/fields.py +2065 -0
  58. pboot_validator/functional_serializers.py +461 -0
  59. pboot_validator/functional_validators.py +920 -0
  60. pboot_validator/generics.py +5 -0
  61. pboot_validator/json.py +5 -0
  62. pboot_validator/json_schema.py +3283 -0
  63. pboot_validator/main.py +1947 -0
  64. pboot_validator/mypy.py +1469 -0
  65. pboot_validator/networks.py +1417 -0
  66. pboot_validator/parse.py +5 -0
  67. pboot_validator/plugin/__init__.py +190 -0
  68. pboot_validator/plugin/_loader.py +56 -0
  69. pboot_validator/plugin/_schema_validator.py +152 -0
  70. pboot_validator/py.typed +0 -0
  71. pboot_validator/root_model.py +189 -0
  72. pboot_validator/schema.py +5 -0
  73. pboot_validator/tools.py +5 -0
  74. pboot_validator/type_adapter.py +780 -0
  75. pboot_validator/types.py +3405 -0
  76. pboot_validator/typing.py +5 -0
  77. pboot_validator/utils.py +5 -0
  78. pboot_validator/v1/__init__.py +131 -0
  79. pboot_validator/v1/_hypothesis_plugin.py +391 -0
  80. pboot_validator/v1/annotated_types.py +72 -0
  81. pboot_validator/v1/class_validators.py +361 -0
  82. pboot_validator/v1/color.py +494 -0
  83. pboot_validator/v1/config.py +191 -0
  84. pboot_validator/v1/dataclasses.py +503 -0
  85. pboot_validator/v1/datetime_parse.py +248 -0
  86. pboot_validator/v1/decorator.py +264 -0
  87. pboot_validator/v1/env_settings.py +350 -0
  88. pboot_validator/v1/error_wrappers.py +161 -0
  89. pboot_validator/v1/errors.py +646 -0
  90. pboot_validator/v1/fields.py +1253 -0
  91. pboot_validator/v1/generics.py +400 -0
  92. pboot_validator/v1/json.py +112 -0
  93. pboot_validator/v1/main.py +1130 -0
  94. pboot_validator/v1/mypy.py +950 -0
  95. pboot_validator/v1/networks.py +747 -0
  96. pboot_validator/v1/parse.py +66 -0
  97. pboot_validator/v1/py.typed +0 -0
  98. pboot_validator/v1/schema.py +1163 -0
  99. pboot_validator/v1/tools.py +92 -0
  100. pboot_validator/v1/types.py +1213 -0
  101. pboot_validator/v1/typing.py +627 -0
  102. pboot_validator/v1/utils.py +807 -0
  103. pboot_validator/v1/validators.py +768 -0
  104. pboot_validator/v1/version.py +38 -0
  105. pboot_validator/validate_call_decorator.py +121 -0
  106. pboot_validator/validators.py +5 -0
  107. pboot_validator/version.py +113 -0
  108. pboot_validator/warnings.py +130 -0
  109. pboot_validator-1.0.0.dist-info/METADATA +93 -0
  110. pboot_validator-1.0.0.dist-info/RECORD +112 -0
  111. pboot_validator-1.0.0.dist-info/WHEEL +4 -0
  112. pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1417 @@
1
+ """The networks module contains types for common network-related fields.
2
+
3
+ /// version-added | v2.12
4
+ By default, validation of URL types add a trailing slash if no path is present:
5
+
6
+ ```python
7
+ from pboot_validator import AnyUrl, BaseModel
8
+
9
+ class Model(BaseModel):
10
+ url: AnyUrl
11
+
12
+ m = Model(url='https://example.com')
13
+ print(m.url)
14
+ #> https://example.com/
15
+ ```
16
+
17
+ The [`url_preserve_empty_path`][pboot_validator.ConfigDict.url_preserve_empty_path] config option can be used
18
+ to control this behavior:
19
+
20
+ ```python
21
+ from pboot_validator import AnyUrl, BaseModel, ConfigDict
22
+
23
+ class Model(BaseModel):
24
+ model_config = ConfigDict(url_preserve_empty_path=True)
25
+
26
+ url: AnyUrl
27
+
28
+ m = Model(url='https://example.com')
29
+ print(m.url)
30
+ #> https://example.com
31
+ ```
32
+ ///
33
+ """
34
+
35
+ from __future__ import annotations as _annotations
36
+
37
+ import dataclasses as _dataclasses
38
+ import re
39
+ from dataclasses import fields
40
+ from functools import lru_cache
41
+ from importlib.metadata import version
42
+ from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
43
+ from typing import TYPE_CHECKING, Annotated, Any, ClassVar, TypeAlias, overload
44
+
45
+ from pydantic_core import (
46
+ MultiHostHost,
47
+ PydanticCustomError,
48
+ PydanticSerializationUnexpectedValue,
49
+ SchemaSerializer,
50
+ core_schema,
51
+ )
52
+ from pydantic_core import MultiHostUrl as _CoreMultiHostUrl
53
+ from pydantic_core import Url as _CoreUrl
54
+ from typing_extensions import Self
55
+
56
+ from pboot_validator.errors import PydanticUserError
57
+
58
+ from ._internal import _repr, _schema_generation_shared
59
+ from ._migration import getattr_migration
60
+ from .annotated_handlers import GetCoreSchemaHandler
61
+ from .json_schema import JsonSchemaValue
62
+ from .type_adapter import TypeAdapter
63
+
64
+ if TYPE_CHECKING:
65
+ import email_validator
66
+
67
+ NetworkType: TypeAlias = 'str | bytes | int | tuple[str | bytes | int, str | int]'
68
+
69
+ else:
70
+ email_validator = None
71
+
72
+
73
+ __all__ = [
74
+ 'AnyUrl',
75
+ 'AnyHttpUrl',
76
+ 'FileUrl',
77
+ 'FtpUrl',
78
+ 'HttpUrl',
79
+ 'WebsocketUrl',
80
+ 'AnyWebsocketUrl',
81
+ 'UrlConstraints',
82
+ 'EmailStr',
83
+ 'NameEmail',
84
+ 'IPvAnyAddress',
85
+ 'IPvAnyInterface',
86
+ 'IPvAnyNetwork',
87
+ 'PostgresDsn',
88
+ 'CockroachDsn',
89
+ 'AmqpDsn',
90
+ 'RedisDsn',
91
+ 'MongoDsn',
92
+ 'KafkaDsn',
93
+ 'NatsDsn',
94
+ 'validate_email',
95
+ 'MySQLDsn',
96
+ 'MariaDBDsn',
97
+ 'ClickHouseDsn',
98
+ 'SnowflakeDsn',
99
+ ]
100
+
101
+
102
+ @_dataclasses.dataclass
103
+ class UrlConstraints:
104
+ """Url constraints.
105
+
106
+ Attributes:
107
+ max_length: The maximum length of the url. Defaults to `None`.
108
+ allowed_schemes: The allowed schemes. Defaults to `None`.
109
+ host_required: Whether the host is required. Defaults to `None`.
110
+ default_host: The default host. Defaults to `None`.
111
+ default_port: The default port. Defaults to `None`.
112
+ default_path: The default path. Defaults to `None`.
113
+ preserve_empty_path: Whether to preserve empty URL paths. Defaults to `None`.
114
+ """
115
+
116
+ max_length: int | None = None
117
+ allowed_schemes: list[str] | None = None
118
+ host_required: bool | None = None
119
+ default_host: str | None = None
120
+ default_port: int | None = None
121
+ default_path: str | None = None
122
+ preserve_empty_path: bool | None = None
123
+
124
+ def __hash__(self) -> int:
125
+ return hash(
126
+ (
127
+ self.max_length,
128
+ tuple(self.allowed_schemes) if self.allowed_schemes is not None else None,
129
+ self.host_required,
130
+ self.default_host,
131
+ self.default_port,
132
+ self.default_path,
133
+ self.preserve_empty_path,
134
+ )
135
+ )
136
+
137
+ @property
138
+ def defined_constraints(self) -> dict[str, Any]:
139
+ """Fetch a key / value mapping of constraints to values that are not None. Used for core schema updates."""
140
+ return {field.name: value for field in fields(self) if (value := getattr(self, field.name)) is not None}
141
+
142
+ def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
143
+ schema = handler(source)
144
+
145
+ # for function-wrap schemas, url constraints is applied to the inner schema
146
+ # because when we generate schemas for urls, we wrap a core_schema.url_schema() with a function-wrap schema
147
+ # that helps with validation on initialization, see _BaseUrl and _BaseMultiHostUrl below.
148
+ schema_to_mutate = schema['schema'] if schema['type'] == 'function-wrap' else schema
149
+ if (annotated_type := schema_to_mutate['type']) not in ('url', 'multi-host-url'):
150
+ raise PydanticUserError(
151
+ f"'UrlConstraints' cannot annotate '{annotated_type}'.", code='invalid-annotated-type'
152
+ )
153
+ for constraint_key, constraint_value in self.defined_constraints.items():
154
+ schema_to_mutate[constraint_key] = constraint_value
155
+ return schema
156
+
157
+
158
+ class _BaseUrl:
159
+ _constraints: ClassVar[UrlConstraints] = UrlConstraints()
160
+ _url: _CoreUrl
161
+
162
+ def __init__(self, url: str | _CoreUrl | _BaseUrl) -> None:
163
+ self._url = _build_type_adapter(self.__class__).validate_python(url)._url
164
+
165
+ @property
166
+ def scheme(self) -> str:
167
+ """The scheme part of the URL.
168
+
169
+ e.g. `https` in `https://user:pass@host:port/path?query#fragment`
170
+ """
171
+ return self._url.scheme
172
+
173
+ @property
174
+ def username(self) -> str | None:
175
+ """The username part of the URL, or `None`.
176
+
177
+ e.g. `user` in `https://user:pass@host:port/path?query#fragment`
178
+ """
179
+ return self._url.username
180
+
181
+ @property
182
+ def password(self) -> str | None:
183
+ """The password part of the URL, or `None`.
184
+
185
+ e.g. `pass` in `https://user:pass@host:port/path?query#fragment`
186
+ """
187
+ return self._url.password
188
+
189
+ @property
190
+ def host(self) -> str | None:
191
+ """The host part of the URL, or `None`.
192
+
193
+ If the URL must be punycode encoded, this is the encoded host, e.g. if the input URL is `https://£££.com`,
194
+ `host` will be `xn--9aaa.com`
195
+ """
196
+ return self._url.host
197
+
198
+ def unicode_host(self) -> str | None:
199
+ """The host part of the URL as a unicode string, or `None`.
200
+
201
+ e.g. `host` in `https://user:pass@host:port/path?query#fragment`
202
+
203
+ If the URL must be punycode encoded, this is the decoded host, e.g. if the input URL is `https://£££.com`,
204
+ `unicode_host()` will be `£££.com`
205
+ """
206
+ return self._url.unicode_host()
207
+
208
+ @property
209
+ def port(self) -> int | None:
210
+ """The port part of the URL, or `None`.
211
+
212
+ e.g. `port` in `https://user:pass@host:port/path?query#fragment`
213
+ """
214
+ return self._url.port
215
+
216
+ @property
217
+ def path(self) -> str | None:
218
+ """The path part of the URL, or `None`.
219
+
220
+ e.g. `/path` in `https://user:pass@host:port/path?query#fragment`
221
+ """
222
+ return self._url.path
223
+
224
+ @property
225
+ def query(self) -> str | None:
226
+ """The query part of the URL, or `None`.
227
+
228
+ e.g. `query` in `https://user:pass@host:port/path?query#fragment`
229
+ """
230
+ return self._url.query
231
+
232
+ def query_params(self) -> list[tuple[str, str]]:
233
+ """The query part of the URL as a list of key-value pairs.
234
+
235
+ e.g. `[('foo', 'bar')]` in `https://user:pass@host:port/path?foo=bar#fragment`
236
+ """
237
+ return self._url.query_params()
238
+
239
+ @property
240
+ def fragment(self) -> str | None:
241
+ """The fragment part of the URL, or `None`.
242
+
243
+ e.g. `fragment` in `https://user:pass@host:port/path?query#fragment`
244
+ """
245
+ return self._url.fragment
246
+
247
+ def unicode_string(self) -> str:
248
+ """The URL as a unicode string, unlike `__str__()` this will not punycode encode the host.
249
+
250
+ If the URL must be punycode encoded, this is the decoded string, e.g. if the input URL is `https://£££.com`,
251
+ `unicode_string()` will be `https://£££.com`
252
+ """
253
+ return self._url.unicode_string()
254
+
255
+ def encoded_string(self) -> str:
256
+ """The URL's encoded string representation via __str__().
257
+
258
+ This returns the punycode-encoded host version of the URL as a string.
259
+ """
260
+ return str(self)
261
+
262
+ def __str__(self) -> str:
263
+ """The URL as a string, this will punycode encode the host if required."""
264
+ return str(self._url)
265
+
266
+ def __repr__(self) -> str:
267
+ return f'{self.__class__.__name__}({str(self._url)!r})'
268
+
269
+ def __deepcopy__(self, memo: dict) -> Self:
270
+ return self.__class__(self._url)
271
+
272
+ def __eq__(self, other: Any) -> bool:
273
+ if self.__class__ is not other.__class__:
274
+ return NotImplemented
275
+ return self._url == other._url
276
+
277
+ def __lt__(self, other: Any) -> bool:
278
+ if self.__class__ is not other.__class__:
279
+ return NotImplemented
280
+ return self._url < other._url
281
+
282
+ def __gt__(self, other: Any) -> bool:
283
+ if self.__class__ is not other.__class__:
284
+ return NotImplemented
285
+ return self._url > other._url
286
+
287
+ def __le__(self, other: Any) -> bool:
288
+ if self.__class__ is not other.__class__:
289
+ return NotImplemented
290
+ return self._url <= other._url
291
+
292
+ def __ge__(self, other: Any) -> bool:
293
+ if self.__class__ is not other.__class__:
294
+ return NotImplemented
295
+ return self._url >= other._url
296
+
297
+ def __hash__(self) -> int:
298
+ return hash(self._url)
299
+
300
+ def __len__(self) -> int:
301
+ return len(str(self._url))
302
+
303
+ @classmethod
304
+ def build(
305
+ cls,
306
+ *,
307
+ scheme: str,
308
+ username: str | None = None,
309
+ password: str | None = None,
310
+ host: str,
311
+ port: int | None = None,
312
+ path: str | None = None,
313
+ query: str | None = None,
314
+ fragment: str | None = None,
315
+ ) -> Self:
316
+ """Build a new `Url` instance from its component parts.
317
+
318
+ Args:
319
+ scheme: The scheme part of the URL.
320
+ username: The username part of the URL, or omit for no username.
321
+ password: The password part of the URL, or omit for no password.
322
+ host: The host part of the URL.
323
+ port: The port part of the URL, or omit for no port.
324
+ path: The path part of the URL, or omit for no path.
325
+ query: The query part of the URL, or omit for no query.
326
+ fragment: The fragment part of the URL, or omit for no fragment.
327
+
328
+ Returns:
329
+ An instance of URL
330
+ """
331
+ return cls(
332
+ _CoreUrl.build(
333
+ scheme=scheme,
334
+ username=username,
335
+ password=password,
336
+ host=host,
337
+ port=port,
338
+ path=path,
339
+ query=query,
340
+ fragment=fragment,
341
+ )
342
+ )
343
+
344
+ @classmethod
345
+ def serialize_url(cls, url: Any, info: core_schema.SerializationInfo) -> str | Self:
346
+ if not isinstance(url, cls):
347
+ raise PydanticSerializationUnexpectedValue(
348
+ f"Expected `{cls}` but got `{type(url)}` with value `'{url}'` - serialized value may not be as expected."
349
+ )
350
+ if info.mode == 'json':
351
+ return str(url)
352
+ return url
353
+
354
+ @classmethod
355
+ def __get_pydantic_core_schema__(
356
+ cls, source: type[_BaseUrl], handler: GetCoreSchemaHandler
357
+ ) -> core_schema.CoreSchema:
358
+ def wrap_val(v, h):
359
+ if isinstance(v, source):
360
+ return v
361
+ if isinstance(v, _BaseUrl):
362
+ v = str(v)
363
+ core_url = h(v)
364
+ instance = source.__new__(source)
365
+ instance._url = core_url
366
+ return instance
367
+
368
+ return core_schema.no_info_wrap_validator_function(
369
+ wrap_val,
370
+ schema=core_schema.url_schema(**cls._constraints.defined_constraints),
371
+ serialization=core_schema.plain_serializer_function_ser_schema(
372
+ cls.serialize_url, info_arg=True, when_used='always'
373
+ ),
374
+ )
375
+
376
+ @classmethod
377
+ def __get_pydantic_json_schema__(
378
+ cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
379
+ ) -> JsonSchemaValue:
380
+ # we use the url schema for json schema generation, but we might have to extract it from
381
+ # the function-wrap schema we use as a tool for validation on initialization
382
+ inner_schema = core_schema['schema'] if core_schema['type'] == 'function-wrap' else core_schema
383
+ return handler(inner_schema)
384
+
385
+ __pydantic_serializer__ = SchemaSerializer(core_schema.any_schema(serialization=core_schema.to_string_ser_schema()))
386
+
387
+
388
+ class _BaseMultiHostUrl:
389
+ _constraints: ClassVar[UrlConstraints] = UrlConstraints()
390
+ _url: _CoreMultiHostUrl
391
+
392
+ def __init__(self, url: str | _CoreMultiHostUrl | _BaseMultiHostUrl) -> None:
393
+ self._url = _build_type_adapter(self.__class__).validate_python(url)._url
394
+
395
+ @property
396
+ def scheme(self) -> str:
397
+ """The scheme part of the URL.
398
+
399
+ e.g. `https` in `https://foo.com,bar.com/path?query#fragment`
400
+ """
401
+ return self._url.scheme
402
+
403
+ @property
404
+ def path(self) -> str | None:
405
+ """The path part of the URL, or `None`.
406
+
407
+ e.g. `/path` in `https://foo.com,bar.com/path?query#fragment`
408
+ """
409
+ return self._url.path
410
+
411
+ @property
412
+ def query(self) -> str | None:
413
+ """The query part of the URL, or `None`.
414
+
415
+ e.g. `query` in `https://foo.com,bar.com/path?query#fragment`
416
+ """
417
+ return self._url.query
418
+
419
+ def query_params(self) -> list[tuple[str, str]]:
420
+ """The query part of the URL as a list of key-value pairs.
421
+
422
+ e.g. `[('foo', 'bar')]` in `https://foo.com,bar.com/path?foo=bar#fragment`
423
+ """
424
+ return self._url.query_params()
425
+
426
+ @property
427
+ def fragment(self) -> str | None:
428
+ """The fragment part of the URL, or `None`.
429
+
430
+ e.g. `fragment` in `https://foo.com,bar.com/path?query#fragment`
431
+ """
432
+ return self._url.fragment
433
+
434
+ def hosts(self) -> list[MultiHostHost]:
435
+ '''The hosts of the `MultiHostUrl` as [`MultiHostHost`][pydantic_core.MultiHostHost] typed dicts.
436
+
437
+ ```python
438
+ from pydantic_core import MultiHostUrl
439
+
440
+ mhu = MultiHostUrl('https://foo.com:123,foo:bar@bar.com/path')
441
+ print(mhu.hosts())
442
+ """
443
+ [
444
+ {'username': None, 'password': None, 'host': 'foo.com', 'port': 123},
445
+ {'username': 'foo', 'password': 'bar', 'host': 'bar.com', 'port': 443}
446
+ ]
447
+ ```
448
+ Returns:
449
+ A list of dicts, each representing a host.
450
+ '''
451
+ return self._url.hosts()
452
+
453
+ def encoded_string(self) -> str:
454
+ """The URL's encoded string representation via __str__().
455
+
456
+ This returns the punycode-encoded host version of the URL as a string.
457
+ """
458
+ return str(self)
459
+
460
+ def unicode_string(self) -> str:
461
+ """The URL as a unicode string, unlike `__str__()` this will not punycode encode the hosts."""
462
+ return self._url.unicode_string()
463
+
464
+ def __str__(self) -> str:
465
+ """The URL as a string, this will punycode encode the host if required."""
466
+ return str(self._url)
467
+
468
+ def __repr__(self) -> str:
469
+ return f'{self.__class__.__name__}({str(self._url)!r})'
470
+
471
+ def __deepcopy__(self, memo: dict) -> Self:
472
+ return self.__class__(self._url)
473
+
474
+ def __eq__(self, other: Any) -> bool:
475
+ if self.__class__ is not other.__class__:
476
+ return NotImplemented
477
+ return self._url == other._url
478
+
479
+ def __hash__(self) -> int:
480
+ return hash(self._url)
481
+
482
+ def __len__(self) -> int:
483
+ return len(str(self._url))
484
+
485
+ @classmethod
486
+ @overload
487
+ def build(
488
+ cls,
489
+ *,
490
+ scheme: str,
491
+ hosts: list[MultiHostHost],
492
+ username: None = None,
493
+ password: None = None,
494
+ host: None = None,
495
+ port: None = None,
496
+ path: str | None = None,
497
+ query: str | None = None,
498
+ fragment: str | None = None,
499
+ ) -> Self: ...
500
+ @classmethod
501
+ @overload
502
+ def build(
503
+ cls,
504
+ *,
505
+ scheme: str,
506
+ hosts: None = None,
507
+ host: str,
508
+ username: str | None = None,
509
+ password: str | None = None,
510
+ port: int | None = None,
511
+ path: str | None = None,
512
+ query: str | None = None,
513
+ fragment: str | None = None,
514
+ ) -> Self: ...
515
+ @classmethod
516
+ def build(
517
+ cls,
518
+ *,
519
+ scheme: str,
520
+ hosts: list[MultiHostHost] | None = None,
521
+ username: str | None = None,
522
+ password: str | None = None,
523
+ host: str | None = None,
524
+ port: int | None = None,
525
+ path: str | None = None,
526
+ query: str | None = None,
527
+ fragment: str | None = None,
528
+ ) -> Self:
529
+ """Build a new `MultiHostUrl` instance from its component parts.
530
+
531
+ This method takes either `hosts` - a list of `MultiHostHost` typed dicts, or the individual components
532
+ `username`, `password`, `host` and `port`.
533
+
534
+ Args:
535
+ scheme: The scheme part of the URL.
536
+ hosts: Multiple hosts to build the URL from.
537
+ username: The username part of the URL.
538
+ password: The password part of the URL.
539
+ host: The host part of the URL.
540
+ port: The port part of the URL.
541
+ path: The path part of the URL.
542
+ query: The query part of the URL, or omit for no query.
543
+ fragment: The fragment part of the URL, or omit for no fragment.
544
+
545
+ Returns:
546
+ An instance of `MultiHostUrl`
547
+ """
548
+ return cls(
549
+ _CoreMultiHostUrl.build( # pyright: ignore[reportCallIssue]
550
+ scheme=scheme,
551
+ hosts=hosts, # pyright: ignore[reportArgumentType]
552
+ username=username,
553
+ password=password,
554
+ host=host, # pyright: ignore[reportArgumentType]
555
+ port=port,
556
+ path=path,
557
+ query=query,
558
+ fragment=fragment,
559
+ )
560
+ )
561
+
562
+ @classmethod
563
+ def serialize_url(cls, url: Any, info: core_schema.SerializationInfo) -> str | Self:
564
+ if not isinstance(url, cls):
565
+ raise PydanticSerializationUnexpectedValue(
566
+ f"Expected `{cls}` but got `{type(url)}` with value `'{url}'` - serialized value may not be as expected."
567
+ )
568
+ if info.mode == 'json':
569
+ return str(url)
570
+ return url
571
+
572
+ @classmethod
573
+ def __get_pydantic_core_schema__(
574
+ cls, source: type[_BaseMultiHostUrl], handler: GetCoreSchemaHandler
575
+ ) -> core_schema.CoreSchema:
576
+ def wrap_val(v, h):
577
+ if isinstance(v, source):
578
+ return v
579
+ if isinstance(v, _BaseMultiHostUrl):
580
+ v = str(v)
581
+ core_url = h(v)
582
+ instance = source.__new__(source)
583
+ instance._url = core_url
584
+ return instance
585
+
586
+ return core_schema.no_info_wrap_validator_function(
587
+ wrap_val,
588
+ schema=core_schema.multi_host_url_schema(**cls._constraints.defined_constraints),
589
+ serialization=core_schema.plain_serializer_function_ser_schema(
590
+ cls.serialize_url, info_arg=True, when_used='always'
591
+ ),
592
+ )
593
+
594
+ @classmethod
595
+ def __get_pydantic_json_schema__(
596
+ cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
597
+ ) -> JsonSchemaValue:
598
+ # we use the url schema for json schema generation, but we might have to extract it from
599
+ # the function-wrap schema we use as a tool for validation on initialization
600
+ inner_schema = core_schema['schema'] if core_schema['type'] == 'function-wrap' else core_schema
601
+ return handler(inner_schema)
602
+
603
+ __pydantic_serializer__ = SchemaSerializer(core_schema.any_schema(serialization=core_schema.to_string_ser_schema()))
604
+
605
+
606
+ @lru_cache
607
+ def _build_type_adapter(cls: type[_BaseUrl | _BaseMultiHostUrl]) -> TypeAdapter:
608
+ return TypeAdapter(cls)
609
+
610
+
611
+ class AnyUrl(_BaseUrl):
612
+ """Base type for all URLs.
613
+
614
+ * Any scheme allowed
615
+ * Top-level domain (TLD) not required
616
+ * Host not required
617
+
618
+ Assuming an input URL of `http://samuel:pass@example.com:8000/the/path/?query=here#fragment=is;this=bit`,
619
+ the types export the following properties:
620
+
621
+ - `scheme`: the URL scheme (`http`), always set.
622
+ - `host`: the URL host (`example.com`).
623
+ - `username`: optional username if included (`samuel`).
624
+ - `password`: optional password if included (`pass`).
625
+ - `port`: optional port (`8000`).
626
+ - `path`: optional path (`/the/path/`).
627
+ - `query`: optional URL query (for example, `GET` arguments or "search string", such as `query=here`).
628
+ - `fragment`: optional fragment (`fragment=is;this=bit`).
629
+ """
630
+
631
+
632
+ # Note: all single host urls inherit from `AnyUrl` to preserve compatibility with pre-v2.10 code
633
+ # Where urls were annotated variants of `AnyUrl`, which was an alias to `pydantic_core.Url`
634
+
635
+
636
+ class AnyHttpUrl(AnyUrl):
637
+ """A type that will accept any http or https URL.
638
+
639
+ * TLD not required
640
+ * Host not required
641
+ """
642
+
643
+ _constraints = UrlConstraints(allowed_schemes=['http', 'https'])
644
+
645
+
646
+ class HttpUrl(AnyUrl):
647
+ """A type that will accept any http or https URL.
648
+
649
+ * TLD not required
650
+ * Host not required
651
+ * Max length 2083
652
+
653
+ ```python
654
+ from pboot_validator import BaseModel, HttpUrl, ValidationError
655
+
656
+ class MyModel(BaseModel):
657
+ url: HttpUrl
658
+
659
+ m = MyModel(url='http://www.example.com') # (1)!
660
+ print(m.url)
661
+ #> http://www.example.com/
662
+
663
+ try:
664
+ MyModel(url='ftp://invalid.url')
665
+ except ValidationError as e:
666
+ print(e)
667
+ '''
668
+ 1 validation error for MyModel
669
+ url
670
+ URL scheme should be 'http' or 'https' [type=url_scheme, input_value='ftp://invalid.url', input_type=str]
671
+ '''
672
+
673
+ try:
674
+ MyModel(url='not a url')
675
+ except ValidationError as e:
676
+ print(e)
677
+ '''
678
+ 1 validation error for MyModel
679
+ url
680
+ Input should be a valid URL, relative URL without a base [type=url_parsing, input_value='not a url', input_type=str]
681
+ '''
682
+ ```
683
+
684
+ 1. Note: mypy would prefer `m = MyModel(url=HttpUrl('http://www.example.com'))`, but Pydantic will convert the string to an HttpUrl instance anyway.
685
+
686
+ "International domains" (e.g. a URL where the host or TLD includes non-ascii characters) will be encoded via
687
+ [punycode](https://en.wikipedia.org/wiki/Punycode) (see
688
+ [this article](https://www.xudongz.com/blog/2017/idn-phishing/) for a good description of why this is important):
689
+
690
+ ```python
691
+ from pboot_validator import BaseModel, HttpUrl
692
+
693
+ class MyModel(BaseModel):
694
+ url: HttpUrl
695
+
696
+ m1 = MyModel(url='http://puny£code.com')
697
+ print(m1.url)
698
+ #> http://xn--punycode-eja.com/
699
+ m2 = MyModel(url='https://www.аррӏе.com/')
700
+ print(m2.url)
701
+ #> https://www.xn--80ak6aa92e.com/
702
+ m3 = MyModel(url='https://www.example.珠宝/')
703
+ print(m3.url)
704
+ #> https://www.example.xn--pbt977c/
705
+ ```
706
+
707
+
708
+ !!! warning "Underscores in Hostnames"
709
+ In Pydantic, underscores are allowed in all parts of a domain except the TLD.
710
+ Technically this might be wrong - in theory the hostname cannot have underscores, but subdomains can.
711
+
712
+ To explain this; consider the following two cases:
713
+
714
+ - `exam_ple.co.uk`: the hostname is `exam_ple`, which should not be allowed since it contains an underscore.
715
+ - `foo_bar.example.com` the hostname is `example`, which should be allowed since the underscore is in the subdomain.
716
+
717
+ Without having an exhaustive list of TLDs, it would be impossible to differentiate between these two. Therefore
718
+ underscores are allowed, but you can always do further validation in a validator if desired.
719
+
720
+ Also, Chrome, Firefox, and Safari all currently accept `http://exam_ple.com` as a URL, so we're in good
721
+ (or at least big) company.
722
+ """
723
+
724
+ _constraints = UrlConstraints(max_length=2083, allowed_schemes=['http', 'https'])
725
+
726
+
727
+ class AnyWebsocketUrl(AnyUrl):
728
+ """A type that will accept any ws or wss URL.
729
+
730
+ * TLD not required
731
+ * Host not required
732
+ """
733
+
734
+ _constraints = UrlConstraints(allowed_schemes=['ws', 'wss'])
735
+
736
+
737
+ class WebsocketUrl(AnyUrl):
738
+ """A type that will accept any ws or wss URL.
739
+
740
+ * TLD not required
741
+ * Host not required
742
+ * Max length 2083
743
+ """
744
+
745
+ _constraints = UrlConstraints(max_length=2083, allowed_schemes=['ws', 'wss'])
746
+
747
+
748
+ class FileUrl(AnyUrl):
749
+ """A type that will accept any file URL.
750
+
751
+ * Host not required
752
+ """
753
+
754
+ _constraints = UrlConstraints(allowed_schemes=['file'])
755
+
756
+
757
+ class FtpUrl(AnyUrl):
758
+ """A type that will accept ftp URL.
759
+
760
+ * TLD not required
761
+ * Host not required
762
+ """
763
+
764
+ _constraints = UrlConstraints(allowed_schemes=['ftp'])
765
+
766
+
767
+ class PostgresDsn(_BaseMultiHostUrl):
768
+ """A type that will accept any Postgres DSN.
769
+
770
+ * User info required
771
+ * TLD not required
772
+ * Host required
773
+ * Supports multiple hosts
774
+
775
+ If further validation is required, these properties can be used by validators to enforce specific behaviour:
776
+
777
+ ```python
778
+ from pboot_validator import (
779
+ BaseModel,
780
+ HttpUrl,
781
+ PostgresDsn,
782
+ ValidationError,
783
+ field_validator,
784
+ )
785
+
786
+ class MyModel(BaseModel):
787
+ url: HttpUrl
788
+
789
+ m = MyModel(url='http://www.example.com')
790
+
791
+ # the repr() method for a url will display all properties of the url
792
+ print(repr(m.url))
793
+ #> HttpUrl('http://www.example.com/')
794
+ print(m.url.scheme)
795
+ #> http
796
+ print(m.url.host)
797
+ #> www.example.com
798
+ print(m.url.port)
799
+ #> 80
800
+
801
+ class MyDatabaseModel(BaseModel):
802
+ db: PostgresDsn
803
+
804
+ @field_validator('db')
805
+ def check_db_name(cls, v):
806
+ assert v.path and len(v.path) > 1, 'database must be provided'
807
+ return v
808
+
809
+ m = MyDatabaseModel(db='postgres://user:pass@localhost:5432/foobar')
810
+ print(m.db)
811
+ #> postgres://user:pass@localhost:5432/foobar
812
+
813
+ try:
814
+ MyDatabaseModel(db='postgres://user:pass@localhost:5432')
815
+ except ValidationError as e:
816
+ print(e)
817
+ '''
818
+ 1 validation error for MyDatabaseModel
819
+ db
820
+ Assertion failed, database must be provided
821
+ assert (None)
822
+ + where None = PostgresDsn('postgres://user:pass@localhost:5432').path [type=assertion_error, input_value='postgres://user:pass@localhost:5432', input_type=str]
823
+ '''
824
+ ```
825
+ """
826
+
827
+ _constraints = UrlConstraints(
828
+ host_required=True,
829
+ allowed_schemes=[
830
+ 'postgres',
831
+ 'postgresql',
832
+ 'postgresql+asyncpg',
833
+ 'postgresql+pg8000',
834
+ 'postgresql+psycopg',
835
+ 'postgresql+psycopg2',
836
+ 'postgresql+psycopg2cffi',
837
+ 'postgresql+py-postgresql',
838
+ 'postgresql+pygresql',
839
+ ],
840
+ )
841
+
842
+ @property
843
+ def host(self) -> str:
844
+ """The required URL host."""
845
+ return self._url.host # pyright: ignore[reportAttributeAccessIssue]
846
+
847
+
848
+ class CockroachDsn(AnyUrl):
849
+ """A type that will accept any Cockroach DSN.
850
+
851
+ * User info required
852
+ * TLD not required
853
+ * Host required
854
+ """
855
+
856
+ _constraints = UrlConstraints(
857
+ host_required=True,
858
+ allowed_schemes=[
859
+ 'cockroachdb',
860
+ 'cockroachdb+psycopg2',
861
+ 'cockroachdb+asyncpg',
862
+ ],
863
+ )
864
+
865
+ @property
866
+ def host(self) -> str:
867
+ """The required URL host."""
868
+ return self._url.host # pyright: ignore[reportReturnType]
869
+
870
+
871
+ class AmqpDsn(AnyUrl):
872
+ """A type that will accept any AMQP DSN.
873
+
874
+ * User info required
875
+ * TLD not required
876
+ * Host not required
877
+ """
878
+
879
+ _constraints = UrlConstraints(allowed_schemes=['amqp', 'amqps'])
880
+
881
+
882
+ class RedisDsn(AnyUrl):
883
+ """A type that will accept any Redis DSN.
884
+
885
+ * User info required
886
+ * TLD not required
887
+ * Host required (e.g., `rediss://:pass@localhost`)
888
+ """
889
+
890
+ _constraints = UrlConstraints(
891
+ allowed_schemes=['redis', 'rediss'],
892
+ default_host='localhost',
893
+ default_port=6379,
894
+ default_path='/0',
895
+ host_required=True,
896
+ )
897
+
898
+ @property
899
+ def host(self) -> str:
900
+ """The required URL host."""
901
+ return self._url.host # pyright: ignore[reportReturnType]
902
+
903
+
904
+ class MongoDsn(_BaseMultiHostUrl):
905
+ """A type that will accept any MongoDB DSN.
906
+
907
+ * User info not required
908
+ * Database name not required
909
+ * Port not required
910
+ * User info may be passed without user part (e.g., `mongodb://mongodb0.example.com:27017`).
911
+
912
+ !!! warning
913
+ If a port isn't specified, the default MongoDB port `27017` will be used. If this behavior is
914
+ undesirable, you can use the following:
915
+
916
+ ```python
917
+ from typing import Annotated
918
+
919
+ from pydantic_core import MultiHostUrl
920
+
921
+ from pboot_validator import UrlConstraints
922
+
923
+ MongoDsnNoDefaultPort = Annotated[
924
+ MultiHostUrl,
925
+ UrlConstraints(allowed_schemes=['mongodb', 'mongodb+srv']),
926
+ ]
927
+ ```
928
+ """
929
+
930
+ _constraints = UrlConstraints(allowed_schemes=['mongodb', 'mongodb+srv'], default_port=27017)
931
+
932
+
933
+ class KafkaDsn(AnyUrl):
934
+ """A type that will accept any Kafka DSN.
935
+
936
+ * User info required
937
+ * TLD not required
938
+ * Host not required
939
+ """
940
+
941
+ _constraints = UrlConstraints(allowed_schemes=['kafka'], default_host='localhost', default_port=9092)
942
+
943
+
944
+ class NatsDsn(_BaseMultiHostUrl):
945
+ """A type that will accept any NATS DSN.
946
+
947
+ NATS is a connective technology built for the ever increasingly hyper-connected world.
948
+ It is a single technology that enables applications to securely communicate across
949
+ any combination of cloud vendors, on-premise, edge, web and mobile, and devices.
950
+ More: https://nats.io
951
+ """
952
+
953
+ _constraints = UrlConstraints(
954
+ allowed_schemes=['nats', 'tls', 'ws', 'wss'], default_host='localhost', default_port=4222
955
+ )
956
+
957
+
958
+ class MySQLDsn(AnyUrl):
959
+ """A type that will accept any MySQL DSN.
960
+
961
+ * User info required
962
+ * TLD not required
963
+ * Host not required
964
+ """
965
+
966
+ _constraints = UrlConstraints(
967
+ allowed_schemes=[
968
+ 'mysql',
969
+ 'mysql+mysqlconnector',
970
+ 'mysql+aiomysql',
971
+ 'mysql+asyncmy',
972
+ 'mysql+mysqldb',
973
+ 'mysql+pymysql',
974
+ 'mysql+cymysql',
975
+ 'mysql+pyodbc',
976
+ ],
977
+ default_port=3306,
978
+ host_required=True,
979
+ )
980
+
981
+
982
+ class MariaDBDsn(AnyUrl):
983
+ """A type that will accept any MariaDB DSN.
984
+
985
+ * User info required
986
+ * TLD not required
987
+ * Host not required
988
+ """
989
+
990
+ _constraints = UrlConstraints(
991
+ allowed_schemes=['mariadb', 'mariadb+mariadbconnector', 'mariadb+pymysql'],
992
+ default_port=3306,
993
+ )
994
+
995
+
996
+ class ClickHouseDsn(AnyUrl):
997
+ """A type that will accept any ClickHouse DSN.
998
+
999
+ * User info required
1000
+ * TLD not required
1001
+ * Host not required
1002
+ """
1003
+
1004
+ _constraints = UrlConstraints(
1005
+ allowed_schemes=[
1006
+ 'clickhouse+native',
1007
+ 'clickhouse+asynch',
1008
+ 'clickhouse+http',
1009
+ 'clickhouse',
1010
+ 'clickhouses',
1011
+ 'clickhousedb',
1012
+ ],
1013
+ default_host='localhost',
1014
+ default_port=9000,
1015
+ )
1016
+
1017
+
1018
+ class SnowflakeDsn(AnyUrl):
1019
+ """A type that will accept any Snowflake DSN.
1020
+
1021
+ * User info required
1022
+ * TLD not required
1023
+ * Host required
1024
+ """
1025
+
1026
+ _constraints = UrlConstraints(
1027
+ allowed_schemes=['snowflake'],
1028
+ host_required=True,
1029
+ )
1030
+
1031
+ @property
1032
+ def host(self) -> str:
1033
+ """The required URL host."""
1034
+ return self._url.host # pyright: ignore[reportReturnType]
1035
+
1036
+
1037
+ def import_email_validator() -> None:
1038
+ global email_validator
1039
+ try:
1040
+ import email_validator
1041
+ except ImportError as e:
1042
+ raise ImportError("email-validator is not installed, run `pip install 'pydantic[email]'`") from e
1043
+ if not version('email-validator').partition('.')[0] == '2':
1044
+ raise ImportError('email-validator version >= 2.0 required, run pip install -U email-validator')
1045
+
1046
+
1047
+ if TYPE_CHECKING:
1048
+ EmailStr = Annotated[str, ...]
1049
+ else:
1050
+
1051
+ class EmailStr:
1052
+ """
1053
+ Info:
1054
+ To use this type, you need to install the optional
1055
+ [`email-validator`](https://github.com/JoshData/python-email-validator) package:
1056
+
1057
+ ```bash
1058
+ pip install email-validator
1059
+ ```
1060
+
1061
+ Validate email addresses.
1062
+
1063
+ ```python
1064
+ from pboot_validator import BaseModel, EmailStr
1065
+
1066
+ class Model(BaseModel):
1067
+ email: EmailStr
1068
+
1069
+ print(Model(email='contact@mail.com'))
1070
+ #> email='contact@mail.com'
1071
+ ```
1072
+ """ # noqa: D212
1073
+
1074
+ @classmethod
1075
+ def __get_pydantic_core_schema__(
1076
+ cls,
1077
+ _source: type[Any],
1078
+ _handler: GetCoreSchemaHandler,
1079
+ ) -> core_schema.CoreSchema:
1080
+ import_email_validator()
1081
+ return core_schema.no_info_after_validator_function(cls._validate, core_schema.str_schema())
1082
+
1083
+ @classmethod
1084
+ def __get_pydantic_json_schema__(
1085
+ cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
1086
+ ) -> JsonSchemaValue:
1087
+ field_schema = handler(core_schema)
1088
+ field_schema.update(type='string', format='email')
1089
+ return field_schema
1090
+
1091
+ @classmethod
1092
+ def _validate(cls, input_value: str, /) -> str:
1093
+ return validate_email(input_value)[1]
1094
+
1095
+
1096
+ class NameEmail(_repr.Representation):
1097
+ """
1098
+ Info:
1099
+ To use this type, you need to install the optional
1100
+ [`email-validator`](https://github.com/JoshData/python-email-validator) package:
1101
+
1102
+ ```bash
1103
+ pip install email-validator
1104
+ ```
1105
+
1106
+ Validate a name and email address combination, as specified by
1107
+ [RFC 5322](https://datatracker.ietf.org/doc/html/rfc5322#section-3.4).
1108
+
1109
+ The `NameEmail` has two properties: `name` and `email`.
1110
+ In case the `name` is not provided, it's inferred from the email address.
1111
+
1112
+ ```python
1113
+ from pboot_validator import BaseModel, NameEmail
1114
+
1115
+ class User(BaseModel):
1116
+ email: NameEmail
1117
+
1118
+ user = User(email='Fred Bloggs <fred.bloggs@example.com>')
1119
+ print(user.email)
1120
+ #> Fred Bloggs <fred.bloggs@example.com>
1121
+ print(user.email.name)
1122
+ #> Fred Bloggs
1123
+
1124
+ user = User(email='fred.bloggs@example.com')
1125
+ print(user.email)
1126
+ #> fred.bloggs <fred.bloggs@example.com>
1127
+ print(user.email.name)
1128
+ #> fred.bloggs
1129
+ ```
1130
+ """ # noqa: D212
1131
+
1132
+ __slots__ = 'name', 'email'
1133
+
1134
+ def __init__(self, name: str, email: str):
1135
+ self.name = name
1136
+ self.email = email
1137
+
1138
+ def __eq__(self, other: Any) -> bool:
1139
+ return isinstance(other, NameEmail) and (self.name, self.email) == (other.name, other.email)
1140
+
1141
+ @classmethod
1142
+ def __get_pydantic_json_schema__(
1143
+ cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
1144
+ ) -> JsonSchemaValue:
1145
+ field_schema = handler(core_schema)
1146
+ field_schema.update(type='string', format='name-email')
1147
+ return field_schema
1148
+
1149
+ @classmethod
1150
+ def __get_pydantic_core_schema__(
1151
+ cls,
1152
+ _source: type[Any],
1153
+ _handler: GetCoreSchemaHandler,
1154
+ ) -> core_schema.CoreSchema:
1155
+ import_email_validator()
1156
+
1157
+ return core_schema.no_info_after_validator_function(
1158
+ cls._validate,
1159
+ core_schema.json_or_python_schema(
1160
+ json_schema=core_schema.str_schema(),
1161
+ python_schema=core_schema.union_schema(
1162
+ [core_schema.is_instance_schema(cls), core_schema.str_schema()],
1163
+ custom_error_type='name_email_type',
1164
+ custom_error_message='Input is not a valid NameEmail',
1165
+ ),
1166
+ serialization=core_schema.to_string_ser_schema(),
1167
+ ),
1168
+ )
1169
+
1170
+ @classmethod
1171
+ def _validate(cls, input_value: Self | str, /) -> Self:
1172
+ if isinstance(input_value, str):
1173
+ name, email = validate_email(input_value)
1174
+ return cls(name, email)
1175
+ else:
1176
+ return input_value
1177
+
1178
+ def __str__(self) -> str:
1179
+ if '@' in self.name:
1180
+ return f'"{self.name}" <{self.email}>'
1181
+
1182
+ return f'{self.name} <{self.email}>'
1183
+
1184
+
1185
+ IPvAnyAddressType: TypeAlias = 'IPv4Address | IPv6Address'
1186
+ IPvAnyInterfaceType: TypeAlias = 'IPv4Interface | IPv6Interface'
1187
+ IPvAnyNetworkType: TypeAlias = 'IPv4Network | IPv6Network'
1188
+
1189
+ if TYPE_CHECKING:
1190
+ IPvAnyAddress = IPvAnyAddressType
1191
+ IPvAnyInterface = IPvAnyInterfaceType
1192
+ IPvAnyNetwork = IPvAnyNetworkType
1193
+ else:
1194
+
1195
+ class IPvAnyAddress:
1196
+ """Validate an IPv4 or IPv6 address.
1197
+
1198
+ ```python
1199
+ from pboot_validator import BaseModel
1200
+ from pboot_validator.networks import IPvAnyAddress
1201
+
1202
+ class IpModel(BaseModel):
1203
+ ip: IPvAnyAddress
1204
+
1205
+ print(IpModel(ip='127.0.0.1'))
1206
+ #> ip=IPv4Address('127.0.0.1')
1207
+
1208
+ try:
1209
+ IpModel(ip='http://www.example.com')
1210
+ except ValueError as e:
1211
+ print(e.errors())
1212
+ '''
1213
+ [
1214
+ {
1215
+ 'type': 'ip_any_address',
1216
+ 'loc': ('ip',),
1217
+ 'msg': 'value is not a valid IPv4 or IPv6 address',
1218
+ 'input': 'http://www.example.com',
1219
+ }
1220
+ ]
1221
+ '''
1222
+ ```
1223
+ """
1224
+
1225
+ __slots__ = ()
1226
+
1227
+ def __new__(cls, value: Any) -> IPvAnyAddressType:
1228
+ """Validate an IPv4 or IPv6 address."""
1229
+ try:
1230
+ return IPv4Address(value)
1231
+ except ValueError:
1232
+ pass
1233
+
1234
+ try:
1235
+ return IPv6Address(value)
1236
+ except ValueError:
1237
+ raise PydanticCustomError('ip_any_address', 'value is not a valid IPv4 or IPv6 address')
1238
+
1239
+ @classmethod
1240
+ def __get_pydantic_json_schema__(
1241
+ cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
1242
+ ) -> JsonSchemaValue:
1243
+ field_schema = {}
1244
+ field_schema.update(type='string', format='ipvanyaddress')
1245
+ return field_schema
1246
+
1247
+ @classmethod
1248
+ def __get_pydantic_core_schema__(
1249
+ cls,
1250
+ _source: type[Any],
1251
+ _handler: GetCoreSchemaHandler,
1252
+ ) -> core_schema.CoreSchema:
1253
+ return core_schema.no_info_plain_validator_function(
1254
+ cls._validate, serialization=core_schema.to_string_ser_schema()
1255
+ )
1256
+
1257
+ @classmethod
1258
+ def _validate(cls, input_value: Any, /) -> IPvAnyAddressType:
1259
+ return cls(input_value) # type: ignore[return-value]
1260
+
1261
+ class IPvAnyInterface:
1262
+ """Validate an IPv4 or IPv6 interface."""
1263
+
1264
+ __slots__ = ()
1265
+
1266
+ def __new__(cls, value: NetworkType) -> IPvAnyInterfaceType:
1267
+ """Validate an IPv4 or IPv6 interface."""
1268
+ try:
1269
+ return IPv4Interface(value)
1270
+ except ValueError:
1271
+ pass
1272
+
1273
+ try:
1274
+ return IPv6Interface(value)
1275
+ except ValueError:
1276
+ raise PydanticCustomError('ip_any_interface', 'value is not a valid IPv4 or IPv6 interface')
1277
+
1278
+ @classmethod
1279
+ def __get_pydantic_json_schema__(
1280
+ cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
1281
+ ) -> JsonSchemaValue:
1282
+ field_schema = {}
1283
+ field_schema.update(type='string', format='ipvanyinterface')
1284
+ return field_schema
1285
+
1286
+ @classmethod
1287
+ def __get_pydantic_core_schema__(
1288
+ cls,
1289
+ _source: type[Any],
1290
+ _handler: GetCoreSchemaHandler,
1291
+ ) -> core_schema.CoreSchema:
1292
+ return core_schema.no_info_plain_validator_function(
1293
+ cls._validate, serialization=core_schema.to_string_ser_schema()
1294
+ )
1295
+
1296
+ @classmethod
1297
+ def _validate(cls, input_value: NetworkType, /) -> IPvAnyInterfaceType:
1298
+ return cls(input_value) # type: ignore[return-value]
1299
+
1300
+ class IPvAnyNetwork:
1301
+ """Validate an IPv4 or IPv6 network."""
1302
+
1303
+ __slots__ = ()
1304
+
1305
+ def __new__(cls, value: NetworkType) -> IPvAnyNetworkType:
1306
+ """Validate an IPv4 or IPv6 network."""
1307
+ # Assume IP Network is defined with a default value for `strict` argument.
1308
+ # Define your own class if you want to specify network address check strictness.
1309
+ try:
1310
+ return IPv4Network(value)
1311
+ except ValueError:
1312
+ pass
1313
+
1314
+ try:
1315
+ return IPv6Network(value)
1316
+ except ValueError:
1317
+ raise PydanticCustomError('ip_any_network', 'value is not a valid IPv4 or IPv6 network')
1318
+
1319
+ @classmethod
1320
+ def __get_pydantic_json_schema__(
1321
+ cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
1322
+ ) -> JsonSchemaValue:
1323
+ field_schema = {}
1324
+ field_schema.update(type='string', format='ipvanynetwork')
1325
+ return field_schema
1326
+
1327
+ @classmethod
1328
+ def __get_pydantic_core_schema__(
1329
+ cls,
1330
+ _source: type[Any],
1331
+ _handler: GetCoreSchemaHandler,
1332
+ ) -> core_schema.CoreSchema:
1333
+ return core_schema.no_info_plain_validator_function(
1334
+ cls._validate, serialization=core_schema.to_string_ser_schema()
1335
+ )
1336
+
1337
+ @classmethod
1338
+ def _validate(cls, input_value: NetworkType, /) -> IPvAnyNetworkType:
1339
+ return cls(input_value) # type: ignore[return-value]
1340
+
1341
+
1342
+ def _build_pretty_email_regex() -> re.Pattern[str]:
1343
+ name_chars = r'[\w.!#$%&\'*+\-/=?^_`{|}~]'
1344
+ unquoted_name_group = rf'((?:{name_chars}+\s+)*{name_chars}+)'
1345
+ quoted_name_group = r'"((?:[^"]|\")+)"'
1346
+ email_group = r'<(.+)>'
1347
+ return re.compile(rf'\s*(?:{unquoted_name_group}|{quoted_name_group})?\s*{email_group}\s*')
1348
+
1349
+
1350
+ pretty_email_regex = _build_pretty_email_regex()
1351
+
1352
+ MAX_EMAIL_LENGTH = 2048
1353
+ """Maximum length for an email.
1354
+ A somewhat arbitrary but very generous number compared to what is allowed by most implementations.
1355
+ """
1356
+
1357
+
1358
+ def validate_email(value: str) -> tuple[str, str]:
1359
+ """Email address validation using [email-validator](https://pypi.org/project/email-validator/).
1360
+
1361
+ Returns:
1362
+ A tuple containing the local part of the email (or the name for "pretty" email addresses)
1363
+ and the normalized email.
1364
+
1365
+ Raises:
1366
+ PydanticCustomError: If the email is invalid.
1367
+
1368
+ Note:
1369
+ Note that:
1370
+
1371
+ * Raw IP address (literal) domain parts are not allowed.
1372
+ * `"John Doe <local_part@domain.com>"` style "pretty" email addresses are processed.
1373
+ * Spaces are striped from the beginning and end of addresses, but no error is raised.
1374
+ """
1375
+ if email_validator is None:
1376
+ import_email_validator()
1377
+
1378
+ if len(value) > MAX_EMAIL_LENGTH:
1379
+ raise PydanticCustomError(
1380
+ 'value_error',
1381
+ 'value is not a valid email address: {reason}',
1382
+ {'reason': f'Length must not exceed {MAX_EMAIL_LENGTH} characters'},
1383
+ )
1384
+
1385
+ # Carriage returns and line feeds are only allowed in a header field body as part of "folding"
1386
+ # (a CRLF immediately followed by whitespace), which is unfolded before the value is parsed
1387
+ # (see https://www.rfc-editor.org/info/rfc5322/#section-2.2). A `NameEmail` is a standalone value
1388
+ # rather than a folded header line, so any CR or LF is rejected.
1389
+ if '\r' in value or '\n' in value:
1390
+ raise PydanticCustomError(
1391
+ 'value_error',
1392
+ 'value is not a valid email address: {reason}',
1393
+ {'reason': 'Carriage return and line feed characters are not allowed'},
1394
+ )
1395
+
1396
+ m = pretty_email_regex.fullmatch(value)
1397
+ name: str | None = None
1398
+ if m:
1399
+ unquoted_name, quoted_name, value = m.groups()
1400
+ name = unquoted_name or quoted_name
1401
+
1402
+ email = value.strip()
1403
+
1404
+ try:
1405
+ parts = email_validator.validate_email(email, check_deliverability=False)
1406
+ except email_validator.EmailNotValidError as e:
1407
+ raise PydanticCustomError(
1408
+ 'value_error', 'value is not a valid email address: {reason}', {'reason': str(e.args[0])}
1409
+ ) from e
1410
+
1411
+ email = parts.normalized
1412
+ assert email is not None
1413
+ name = name or parts.local_part
1414
+ return name, email
1415
+
1416
+
1417
+ __getattr__ = getattr_migration(__name__)