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,747 @@
1
+ import re
2
+ from ipaddress import (
3
+ IPv4Address,
4
+ IPv4Interface,
5
+ IPv4Network,
6
+ IPv6Address,
7
+ IPv6Interface,
8
+ IPv6Network,
9
+ _BaseAddress,
10
+ _BaseNetwork,
11
+ )
12
+ from typing import (
13
+ TYPE_CHECKING,
14
+ Any,
15
+ Collection,
16
+ Dict,
17
+ Generator,
18
+ List,
19
+ Match,
20
+ Optional,
21
+ Pattern,
22
+ Set,
23
+ Tuple,
24
+ Type,
25
+ Union,
26
+ cast,
27
+ no_type_check,
28
+ )
29
+
30
+ from pboot_validator.v1 import errors
31
+ from pboot_validator.v1.utils import Representation, update_not_none
32
+ from pboot_validator.v1.validators import constr_length_validator, str_validator
33
+
34
+ if TYPE_CHECKING:
35
+ import email_validator
36
+ from typing_extensions import TypedDict
37
+
38
+ from pboot_validator.v1.config import BaseConfig
39
+ from pboot_validator.v1.fields import ModelField
40
+ from pboot_validator.v1.typing import AnyCallable
41
+
42
+ CallableGenerator = Generator[AnyCallable, None, None]
43
+
44
+ class Parts(TypedDict, total=False):
45
+ scheme: str
46
+ user: Optional[str]
47
+ password: Optional[str]
48
+ ipv4: Optional[str]
49
+ ipv6: Optional[str]
50
+ domain: Optional[str]
51
+ port: Optional[str]
52
+ path: Optional[str]
53
+ query: Optional[str]
54
+ fragment: Optional[str]
55
+
56
+ class HostParts(TypedDict, total=False):
57
+ host: str
58
+ tld: Optional[str]
59
+ host_type: Optional[str]
60
+ port: Optional[str]
61
+ rebuild: bool
62
+
63
+ else:
64
+ email_validator = None
65
+
66
+ class Parts(dict):
67
+ pass
68
+
69
+
70
+ NetworkType = Union[str, bytes, int, Tuple[Union[str, bytes, int], Union[str, int]]]
71
+
72
+ __all__ = [
73
+ 'AnyUrl',
74
+ 'AnyHttpUrl',
75
+ 'FileUrl',
76
+ 'HttpUrl',
77
+ 'stricturl',
78
+ 'EmailStr',
79
+ 'NameEmail',
80
+ 'IPvAnyAddress',
81
+ 'IPvAnyInterface',
82
+ 'IPvAnyNetwork',
83
+ 'PostgresDsn',
84
+ 'CockroachDsn',
85
+ 'AmqpDsn',
86
+ 'RedisDsn',
87
+ 'MongoDsn',
88
+ 'KafkaDsn',
89
+ 'validate_email',
90
+ ]
91
+
92
+ _url_regex_cache = None
93
+ _multi_host_url_regex_cache = None
94
+ _ascii_domain_regex_cache = None
95
+ _int_domain_regex_cache = None
96
+ _host_regex_cache = None
97
+
98
+ _host_regex = (
99
+ r'(?:'
100
+ r'(?P<ipv4>(?:\d{1,3}\.){3}\d{1,3})(?=$|[/:#?])|' # ipv4
101
+ r'(?P<ipv6>\[[A-F0-9]*:[A-F0-9:]+\])(?=$|[/:#?])|' # ipv6
102
+ r'(?P<domain>[^\s/:?#]+)' # domain, validation occurs later
103
+ r')?'
104
+ r'(?::(?P<port>\d+))?' # port
105
+ )
106
+ _scheme_regex = r'(?:(?P<scheme>[a-z][a-z0-9+\-.]+)://)?' # scheme https://tools.ietf.org/html/rfc3986#appendix-A
107
+ _user_info_regex = r'(?:(?P<user>[^\s:/]*)(?::(?P<password>[^\s/]*))?@)?'
108
+ _path_regex = r'(?P<path>/[^\s?#]*)?'
109
+ _query_regex = r'(?:\?(?P<query>[^\s#]*))?'
110
+ _fragment_regex = r'(?:#(?P<fragment>[^\s#]*))?'
111
+
112
+
113
+ def url_regex() -> Pattern[str]:
114
+ global _url_regex_cache
115
+ if _url_regex_cache is None:
116
+ _url_regex_cache = re.compile(
117
+ rf'{_scheme_regex}{_user_info_regex}{_host_regex}{_path_regex}{_query_regex}{_fragment_regex}',
118
+ re.IGNORECASE,
119
+ )
120
+ return _url_regex_cache
121
+
122
+
123
+ def multi_host_url_regex() -> Pattern[str]:
124
+ """
125
+ Compiled multi host url regex.
126
+
127
+ Additionally to `url_regex` it allows to match multiple hosts.
128
+ E.g. host1.db.net,host2.db.net
129
+ """
130
+ global _multi_host_url_regex_cache
131
+ if _multi_host_url_regex_cache is None:
132
+ _multi_host_url_regex_cache = re.compile(
133
+ rf'{_scheme_regex}{_user_info_regex}'
134
+ r'(?P<hosts>([^/]*))' # validation occurs later
135
+ rf'{_path_regex}{_query_regex}{_fragment_regex}',
136
+ re.IGNORECASE,
137
+ )
138
+ return _multi_host_url_regex_cache
139
+
140
+
141
+ def ascii_domain_regex() -> Pattern[str]:
142
+ global _ascii_domain_regex_cache
143
+ if _ascii_domain_regex_cache is None:
144
+ ascii_chunk = r'[_0-9a-z](?:[-_0-9a-z]{0,61}[_0-9a-z])?'
145
+ ascii_domain_ending = r'(?P<tld>\.[a-z]{2,63})?\.?'
146
+ _ascii_domain_regex_cache = re.compile(
147
+ fr'(?:{ascii_chunk}\.)*?{ascii_chunk}{ascii_domain_ending}', re.IGNORECASE
148
+ )
149
+ return _ascii_domain_regex_cache
150
+
151
+
152
+ def int_domain_regex() -> Pattern[str]:
153
+ global _int_domain_regex_cache
154
+ if _int_domain_regex_cache is None:
155
+ int_chunk = r'[_0-9a-\U00040000](?:[-_0-9a-\U00040000]{0,61}[_0-9a-\U00040000])?'
156
+ int_domain_ending = r'(?P<tld>(\.[^\W\d_]{2,63})|(\.(?:xn--)[_0-9a-z-]{2,63}))?\.?'
157
+ _int_domain_regex_cache = re.compile(fr'(?:{int_chunk}\.)*?{int_chunk}{int_domain_ending}', re.IGNORECASE)
158
+ return _int_domain_regex_cache
159
+
160
+
161
+ def host_regex() -> Pattern[str]:
162
+ global _host_regex_cache
163
+ if _host_regex_cache is None:
164
+ _host_regex_cache = re.compile(
165
+ _host_regex,
166
+ re.IGNORECASE,
167
+ )
168
+ return _host_regex_cache
169
+
170
+
171
+ class AnyUrl(str):
172
+ strip_whitespace = True
173
+ min_length = 1
174
+ max_length = 2**16
175
+ allowed_schemes: Optional[Collection[str]] = None
176
+ tld_required: bool = False
177
+ user_required: bool = False
178
+ host_required: bool = True
179
+ hidden_parts: Set[str] = set()
180
+
181
+ __slots__ = ('scheme', 'user', 'password', 'host', 'tld', 'host_type', 'port', 'path', 'query', 'fragment')
182
+
183
+ @no_type_check
184
+ def __new__(cls, url: Optional[str], **kwargs) -> object:
185
+ return str.__new__(cls, cls.build(**kwargs) if url is None else url)
186
+
187
+ def __init__(
188
+ self,
189
+ url: str,
190
+ *,
191
+ scheme: str,
192
+ user: Optional[str] = None,
193
+ password: Optional[str] = None,
194
+ host: Optional[str] = None,
195
+ tld: Optional[str] = None,
196
+ host_type: str = 'domain',
197
+ port: Optional[str] = None,
198
+ path: Optional[str] = None,
199
+ query: Optional[str] = None,
200
+ fragment: Optional[str] = None,
201
+ ) -> None:
202
+ str.__init__(url)
203
+ self.scheme = scheme
204
+ self.user = user
205
+ self.password = password
206
+ self.host = host
207
+ self.tld = tld
208
+ self.host_type = host_type
209
+ self.port = port
210
+ self.path = path
211
+ self.query = query
212
+ self.fragment = fragment
213
+
214
+ @classmethod
215
+ def build(
216
+ cls,
217
+ *,
218
+ scheme: str,
219
+ user: Optional[str] = None,
220
+ password: Optional[str] = None,
221
+ host: str,
222
+ port: Optional[str] = None,
223
+ path: Optional[str] = None,
224
+ query: Optional[str] = None,
225
+ fragment: Optional[str] = None,
226
+ **_kwargs: str,
227
+ ) -> str:
228
+ parts = Parts(
229
+ scheme=scheme,
230
+ user=user,
231
+ password=password,
232
+ host=host,
233
+ port=port,
234
+ path=path,
235
+ query=query,
236
+ fragment=fragment,
237
+ **_kwargs, # type: ignore[misc]
238
+ )
239
+
240
+ url = scheme + '://'
241
+ if user:
242
+ url += user
243
+ if password:
244
+ url += ':' + password
245
+ if user or password:
246
+ url += '@'
247
+ url += host
248
+ if port and ('port' not in cls.hidden_parts or cls.get_default_parts(parts).get('port') != port):
249
+ url += ':' + port
250
+ if path:
251
+ url += path
252
+ if query:
253
+ url += '?' + query
254
+ if fragment:
255
+ url += '#' + fragment
256
+ return url
257
+
258
+ @classmethod
259
+ def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
260
+ update_not_none(field_schema, minLength=cls.min_length, maxLength=cls.max_length, format='uri')
261
+
262
+ @classmethod
263
+ def __get_validators__(cls) -> 'CallableGenerator':
264
+ yield cls.validate
265
+
266
+ @classmethod
267
+ def validate(cls, value: Any, field: 'ModelField', config: 'BaseConfig') -> 'AnyUrl':
268
+ if value.__class__ == cls:
269
+ return value
270
+ value = str_validator(value)
271
+ if cls.strip_whitespace:
272
+ value = value.strip()
273
+ url: str = cast(str, constr_length_validator(value, field, config))
274
+
275
+ m = cls._match_url(url)
276
+ # the regex should always match, if it doesn't please report with details of the URL tried
277
+ assert m, 'URL regex failed unexpectedly'
278
+
279
+ original_parts = cast('Parts', m.groupdict())
280
+ parts = cls.apply_default_parts(original_parts)
281
+ parts = cls.validate_parts(parts)
282
+
283
+ if m.end() != len(url):
284
+ raise errors.UrlExtraError(extra=url[m.end() :])
285
+
286
+ return cls._build_url(m, url, parts)
287
+
288
+ @classmethod
289
+ def _build_url(cls, m: Match[str], url: str, parts: 'Parts') -> 'AnyUrl':
290
+ """
291
+ Validate hosts and build the AnyUrl object. Split from `validate` so this method
292
+ can be altered in `MultiHostDsn`.
293
+ """
294
+ host, tld, host_type, rebuild = cls.validate_host(parts)
295
+
296
+ return cls(
297
+ None if rebuild else url,
298
+ scheme=parts['scheme'],
299
+ user=parts['user'],
300
+ password=parts['password'],
301
+ host=host,
302
+ tld=tld,
303
+ host_type=host_type,
304
+ port=parts['port'],
305
+ path=parts['path'],
306
+ query=parts['query'],
307
+ fragment=parts['fragment'],
308
+ )
309
+
310
+ @staticmethod
311
+ def _match_url(url: str) -> Optional[Match[str]]:
312
+ return url_regex().match(url)
313
+
314
+ @staticmethod
315
+ def _validate_port(port: Optional[str]) -> None:
316
+ if port is not None and int(port) > 65_535:
317
+ raise errors.UrlPortError()
318
+
319
+ @classmethod
320
+ def validate_parts(cls, parts: 'Parts', validate_port: bool = True) -> 'Parts':
321
+ """
322
+ A method used to validate parts of a URL.
323
+ Could be overridden to set default values for parts if missing
324
+ """
325
+ scheme = parts['scheme']
326
+ if scheme is None:
327
+ raise errors.UrlSchemeError()
328
+
329
+ if cls.allowed_schemes and scheme.lower() not in cls.allowed_schemes:
330
+ raise errors.UrlSchemePermittedError(set(cls.allowed_schemes))
331
+
332
+ if validate_port:
333
+ cls._validate_port(parts['port'])
334
+
335
+ user = parts['user']
336
+ if cls.user_required and user is None:
337
+ raise errors.UrlUserInfoError()
338
+
339
+ return parts
340
+
341
+ @classmethod
342
+ def validate_host(cls, parts: 'Parts') -> Tuple[str, Optional[str], str, bool]:
343
+ tld, host_type, rebuild = None, None, False
344
+ for f in ('domain', 'ipv4', 'ipv6'):
345
+ host = parts[f] # type: ignore[literal-required]
346
+ if host:
347
+ host_type = f
348
+ break
349
+
350
+ if host is None:
351
+ if cls.host_required:
352
+ raise errors.UrlHostError()
353
+ elif host_type == 'domain':
354
+ is_international = False
355
+ d = ascii_domain_regex().fullmatch(host)
356
+ if d is None:
357
+ d = int_domain_regex().fullmatch(host)
358
+ if d is None:
359
+ raise errors.UrlHostError()
360
+ is_international = True
361
+
362
+ tld = d.group('tld')
363
+ if tld is None and not is_international:
364
+ d = int_domain_regex().fullmatch(host)
365
+ assert d is not None
366
+ tld = d.group('tld')
367
+ is_international = True
368
+
369
+ if tld is not None:
370
+ tld = tld[1:]
371
+ elif cls.tld_required:
372
+ raise errors.UrlHostTldError()
373
+
374
+ if is_international:
375
+ host_type = 'int_domain'
376
+ rebuild = True
377
+ host = host.encode('idna').decode('ascii')
378
+ if tld is not None:
379
+ tld = tld.encode('idna').decode('ascii')
380
+
381
+ return host, tld, host_type, rebuild # type: ignore
382
+
383
+ @staticmethod
384
+ def get_default_parts(parts: 'Parts') -> 'Parts':
385
+ return {}
386
+
387
+ @classmethod
388
+ def apply_default_parts(cls, parts: 'Parts') -> 'Parts':
389
+ for key, value in cls.get_default_parts(parts).items():
390
+ if not parts[key]: # type: ignore[literal-required]
391
+ parts[key] = value # type: ignore[literal-required]
392
+ return parts
393
+
394
+ def __repr__(self) -> str:
395
+ extra = ', '.join(f'{n}={getattr(self, n)!r}' for n in self.__slots__ if getattr(self, n) is not None)
396
+ return f'{self.__class__.__name__}({super().__repr__()}, {extra})'
397
+
398
+
399
+ class AnyHttpUrl(AnyUrl):
400
+ allowed_schemes = {'http', 'https'}
401
+
402
+ __slots__ = ()
403
+
404
+
405
+ class HttpUrl(AnyHttpUrl):
406
+ tld_required = True
407
+ # https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers
408
+ max_length = 2083
409
+ hidden_parts = {'port'}
410
+
411
+ @staticmethod
412
+ def get_default_parts(parts: 'Parts') -> 'Parts':
413
+ return {'port': '80' if parts['scheme'] == 'http' else '443'}
414
+
415
+
416
+ class FileUrl(AnyUrl):
417
+ allowed_schemes = {'file'}
418
+ host_required = False
419
+
420
+ __slots__ = ()
421
+
422
+
423
+ class MultiHostDsn(AnyUrl):
424
+ __slots__ = AnyUrl.__slots__ + ('hosts',)
425
+
426
+ def __init__(self, *args: Any, hosts: Optional[List['HostParts']] = None, **kwargs: Any):
427
+ super().__init__(*args, **kwargs)
428
+ self.hosts = hosts
429
+
430
+ @staticmethod
431
+ def _match_url(url: str) -> Optional[Match[str]]:
432
+ return multi_host_url_regex().match(url)
433
+
434
+ @classmethod
435
+ def validate_parts(cls, parts: 'Parts', validate_port: bool = True) -> 'Parts':
436
+ return super().validate_parts(parts, validate_port=False)
437
+
438
+ @classmethod
439
+ def _build_url(cls, m: Match[str], url: str, parts: 'Parts') -> 'MultiHostDsn':
440
+ hosts_parts: List['HostParts'] = []
441
+ host_re = host_regex()
442
+ for host in m.groupdict()['hosts'].split(','):
443
+ d: Parts = host_re.match(host).groupdict() # type: ignore
444
+ host, tld, host_type, rebuild = cls.validate_host(d)
445
+ port = d.get('port')
446
+ cls._validate_port(port)
447
+ hosts_parts.append(
448
+ {
449
+ 'host': host,
450
+ 'host_type': host_type,
451
+ 'tld': tld,
452
+ 'rebuild': rebuild,
453
+ 'port': port,
454
+ }
455
+ )
456
+
457
+ if len(hosts_parts) > 1:
458
+ return cls(
459
+ None if any([hp['rebuild'] for hp in hosts_parts]) else url,
460
+ scheme=parts['scheme'],
461
+ user=parts['user'],
462
+ password=parts['password'],
463
+ path=parts['path'],
464
+ query=parts['query'],
465
+ fragment=parts['fragment'],
466
+ host_type=None,
467
+ hosts=hosts_parts,
468
+ )
469
+ else:
470
+ # backwards compatibility with single host
471
+ host_part = hosts_parts[0]
472
+ return cls(
473
+ None if host_part['rebuild'] else url,
474
+ scheme=parts['scheme'],
475
+ user=parts['user'],
476
+ password=parts['password'],
477
+ host=host_part['host'],
478
+ tld=host_part['tld'],
479
+ host_type=host_part['host_type'],
480
+ port=host_part.get('port'),
481
+ path=parts['path'],
482
+ query=parts['query'],
483
+ fragment=parts['fragment'],
484
+ )
485
+
486
+
487
+ class PostgresDsn(MultiHostDsn):
488
+ allowed_schemes = {
489
+ 'postgres',
490
+ 'postgresql',
491
+ 'postgresql+asyncpg',
492
+ 'postgresql+pg8000',
493
+ 'postgresql+psycopg',
494
+ 'postgresql+psycopg2',
495
+ 'postgresql+psycopg2cffi',
496
+ 'postgresql+py-postgresql',
497
+ 'postgresql+pygresql',
498
+ }
499
+ user_required = True
500
+
501
+ __slots__ = ()
502
+
503
+
504
+ class CockroachDsn(AnyUrl):
505
+ allowed_schemes = {
506
+ 'cockroachdb',
507
+ 'cockroachdb+psycopg2',
508
+ 'cockroachdb+asyncpg',
509
+ }
510
+ user_required = True
511
+
512
+
513
+ class AmqpDsn(AnyUrl):
514
+ allowed_schemes = {'amqp', 'amqps'}
515
+ host_required = False
516
+
517
+
518
+ class RedisDsn(AnyUrl):
519
+ __slots__ = ()
520
+ allowed_schemes = {'redis', 'rediss'}
521
+ host_required = False
522
+
523
+ @staticmethod
524
+ def get_default_parts(parts: 'Parts') -> 'Parts':
525
+ return {
526
+ 'domain': 'localhost' if not (parts['ipv4'] or parts['ipv6']) else '',
527
+ 'port': '6379',
528
+ 'path': '/0',
529
+ }
530
+
531
+
532
+ class MongoDsn(AnyUrl):
533
+ allowed_schemes = {'mongodb'}
534
+
535
+ # TODO: Needed to generic "Parts" for "Replica Set", "Sharded Cluster", and other mongodb deployment modes
536
+ @staticmethod
537
+ def get_default_parts(parts: 'Parts') -> 'Parts':
538
+ return {
539
+ 'port': '27017',
540
+ }
541
+
542
+
543
+ class KafkaDsn(AnyUrl):
544
+ allowed_schemes = {'kafka'}
545
+
546
+ @staticmethod
547
+ def get_default_parts(parts: 'Parts') -> 'Parts':
548
+ return {
549
+ 'domain': 'localhost',
550
+ 'port': '9092',
551
+ }
552
+
553
+
554
+ def stricturl(
555
+ *,
556
+ strip_whitespace: bool = True,
557
+ min_length: int = 1,
558
+ max_length: int = 2**16,
559
+ tld_required: bool = True,
560
+ host_required: bool = True,
561
+ allowed_schemes: Optional[Collection[str]] = None,
562
+ ) -> Type[AnyUrl]:
563
+ # use kwargs then define conf in a dict to aid with IDE type hinting
564
+ namespace = dict(
565
+ strip_whitespace=strip_whitespace,
566
+ min_length=min_length,
567
+ max_length=max_length,
568
+ tld_required=tld_required,
569
+ host_required=host_required,
570
+ allowed_schemes=allowed_schemes,
571
+ )
572
+ return type('UrlValue', (AnyUrl,), namespace)
573
+
574
+
575
+ def import_email_validator() -> None:
576
+ global email_validator
577
+ try:
578
+ import email_validator
579
+ except ImportError as e:
580
+ raise ImportError('email-validator is not installed, run `pip install pydantic[email]`') from e
581
+
582
+
583
+ class EmailStr(str):
584
+ @classmethod
585
+ def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
586
+ field_schema.update(type='string', format='email')
587
+
588
+ @classmethod
589
+ def __get_validators__(cls) -> 'CallableGenerator':
590
+ # included here and below so the error happens straight away
591
+ import_email_validator()
592
+
593
+ yield str_validator
594
+ yield cls.validate
595
+
596
+ @classmethod
597
+ def validate(cls, value: Union[str]) -> str:
598
+ return validate_email(value)[1]
599
+
600
+
601
+ class NameEmail(Representation):
602
+ __slots__ = 'name', 'email'
603
+
604
+ def __init__(self, name: str, email: str):
605
+ self.name = name
606
+ self.email = email
607
+
608
+ def __eq__(self, other: Any) -> bool:
609
+ return isinstance(other, NameEmail) and (self.name, self.email) == (other.name, other.email)
610
+
611
+ @classmethod
612
+ def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
613
+ field_schema.update(type='string', format='name-email')
614
+
615
+ @classmethod
616
+ def __get_validators__(cls) -> 'CallableGenerator':
617
+ import_email_validator()
618
+
619
+ yield cls.validate
620
+
621
+ @classmethod
622
+ def validate(cls, value: Any) -> 'NameEmail':
623
+ if value.__class__ == cls:
624
+ return value
625
+ value = str_validator(value)
626
+ return cls(*validate_email(value))
627
+
628
+ def __str__(self) -> str:
629
+ return f'{self.name} <{self.email}>'
630
+
631
+
632
+ class IPvAnyAddress(_BaseAddress):
633
+ __slots__ = ()
634
+
635
+ @classmethod
636
+ def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
637
+ field_schema.update(type='string', format='ipvanyaddress')
638
+
639
+ @classmethod
640
+ def __get_validators__(cls) -> 'CallableGenerator':
641
+ yield cls.validate
642
+
643
+ @classmethod
644
+ def validate(cls, value: Union[str, bytes, int]) -> Union[IPv4Address, IPv6Address]:
645
+ try:
646
+ return IPv4Address(value)
647
+ except ValueError:
648
+ pass
649
+
650
+ try:
651
+ return IPv6Address(value)
652
+ except ValueError:
653
+ raise errors.IPvAnyAddressError()
654
+
655
+
656
+ class IPvAnyInterface(_BaseAddress):
657
+ __slots__ = ()
658
+
659
+ @classmethod
660
+ def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
661
+ field_schema.update(type='string', format='ipvanyinterface')
662
+
663
+ @classmethod
664
+ def __get_validators__(cls) -> 'CallableGenerator':
665
+ yield cls.validate
666
+
667
+ @classmethod
668
+ def validate(cls, value: NetworkType) -> Union[IPv4Interface, IPv6Interface]:
669
+ try:
670
+ return IPv4Interface(value)
671
+ except ValueError:
672
+ pass
673
+
674
+ try:
675
+ return IPv6Interface(value)
676
+ except ValueError:
677
+ raise errors.IPvAnyInterfaceError()
678
+
679
+
680
+ class IPvAnyNetwork(_BaseNetwork): # type: ignore
681
+ @classmethod
682
+ def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
683
+ field_schema.update(type='string', format='ipvanynetwork')
684
+
685
+ @classmethod
686
+ def __get_validators__(cls) -> 'CallableGenerator':
687
+ yield cls.validate
688
+
689
+ @classmethod
690
+ def validate(cls, value: NetworkType) -> Union[IPv4Network, IPv6Network]:
691
+ # Assume IP Network is defined with a default value for ``strict`` argument.
692
+ # Define your own class if you want to specify network address check strictness.
693
+ try:
694
+ return IPv4Network(value)
695
+ except ValueError:
696
+ pass
697
+
698
+ try:
699
+ return IPv6Network(value)
700
+ except ValueError:
701
+ raise errors.IPvAnyNetworkError()
702
+
703
+
704
+ pretty_email_regex = re.compile(r'([\w ]*?) *<(.*)> *')
705
+ MAX_EMAIL_LENGTH = 2048
706
+ """Maximum length for an email.
707
+ A somewhat arbitrary but very generous number compared to what is allowed by most implementations.
708
+ """
709
+
710
+
711
+ def validate_email(value: Union[str]) -> Tuple[str, str]:
712
+ """
713
+ Email address validation using https://pypi.org/project/email-validator/
714
+ Notes:
715
+ * raw ip address (literal) domain parts are not allowed.
716
+ * "John Doe <local_part@domain.com>" style "pretty" email addresses are processed
717
+ * spaces are striped from the beginning and end of addresses but no error is raised
718
+ """
719
+ if email_validator is None:
720
+ import_email_validator()
721
+
722
+ if len(value) > MAX_EMAIL_LENGTH:
723
+ raise errors.EmailError()
724
+
725
+ m = pretty_email_regex.fullmatch(value)
726
+ name: Union[str, None] = None
727
+ if m:
728
+ name, value = m.groups()
729
+ email = value.strip()
730
+ try:
731
+ parts = email_validator.validate_email(email, check_deliverability=False)
732
+ except email_validator.EmailNotValidError as e:
733
+ raise errors.EmailError from e
734
+
735
+ if hasattr(parts, 'normalized'):
736
+ # email-validator >= 2
737
+ email = parts.normalized
738
+ assert email is not None
739
+ name = name or parts.local_part
740
+ return name, email
741
+ else:
742
+ # email-validator >1, <2
743
+ at_index = email.index('@')
744
+ local_part = email[:at_index] # RFC 5321, local part must be case-sensitive.
745
+ global_part = email[at_index:].lower()
746
+
747
+ return name or local_part, local_part + global_part