Coverage for pydantic / networks.py: 93.42%

395 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

1"""The networks module contains types for common network-related fields. 

2 

3/// version-added | v2.12 

4By default, validation of URL types add a trailing slash if no path is present: 

5 

6```python 

7from pydantic import AnyUrl, BaseModel 

8 

9class Model(BaseModel): 

10 url: AnyUrl 

11 

12m = Model(url='https://example.com') 

13print(m.url) 

14#> https://example.com/ 

15``` 

16 

17The [`url_preserve_empty_path`][pydantic.ConfigDict.url_preserve_empty_path] config option can be used 

18to control this behavior: 

19 

20```python 

21from pydantic import AnyUrl, BaseModel, ConfigDict 

22 

23class Model(BaseModel): 

24 model_config = ConfigDict(url_preserve_empty_path=True) 

25 

26 url: AnyUrl 

27 

28m = Model(url='https://example.com') 

29print(m.url) 

30#> https://example.com 

31``` 

32/// 

33""" 

34 

35from __future__ import annotations as _annotations 1gabhijkcdlmnoefpqr

36 

37import dataclasses as _dataclasses 1gabhijkcdlmnoefpqr

38import re 1gabhijkcdlmnoefpqr

39from dataclasses import fields 1gabhijkcdlmnoefpqr

40from functools import lru_cache 1gabhijkcdlmnoefpqr

41from importlib.metadata import version 1gabhijkcdlmnoefpqr

42from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network 1gabhijkcdlmnoefpqr

43from typing import TYPE_CHECKING, Annotated, Any, ClassVar, Self, TypeAlias, overload 1gabhijkcdlmnoefpqr

44 

45from pydantic_core import ( 1gabhijkcdlmnoefpqr

46 MultiHostHost, 

47 PydanticCustomError, 

48 PydanticSerializationUnexpectedValue, 

49 SchemaSerializer, 

50 core_schema, 

51) 

52from pydantic_core import MultiHostUrl as _CoreMultiHostUrl 1gabhijkcdlmnoefpqr

53from pydantic_core import Url as _CoreUrl 1gabhijkcdlmnoefpqr

54 

55from pydantic.errors import PydanticUserError 1gabhijkcdlmnoefpqr

56 

57from ._internal import _repr, _schema_generation_shared 1gabhijkcdlmnoefpqr

58from .annotated_handlers import GetCoreSchemaHandler 1gabhijkcdlmnoefpqr

59from .json_schema import JsonSchemaValue 1gabhijkcdlmnoefpqr

60from .type_adapter import TypeAdapter 1gabhijkcdlmnoefpqr

61 

62if TYPE_CHECKING: 1gabhijkcdlmnoefpqr

63 import email_validator 

64 

65 NetworkType: TypeAlias = 'str | bytes | int | tuple[str | bytes | int, str | int]' 

66 

67else: 

68 email_validator = None 1gabhijkcdlmnoefpqr

69 

70 

71__all__ = [ 1gabhijkcdlmnoefpqr

72 'AnyUrl', 

73 'AnyHttpUrl', 

74 'FileUrl', 

75 'FtpUrl', 

76 'HttpUrl', 

77 'WebsocketUrl', 

78 'AnyWebsocketUrl', 

79 'UrlConstraints', 

80 'EmailStr', 

81 'NameEmail', 

82 'IPvAnyAddress', 

83 'IPvAnyInterface', 

84 'IPvAnyNetwork', 

85 'PostgresDsn', 

86 'CockroachDsn', 

87 'AmqpDsn', 

88 'RedisDsn', 

89 'MongoDsn', 

90 'KafkaDsn', 

91 'NatsDsn', 

92 'validate_email', 

93 'MySQLDsn', 

94 'MariaDBDsn', 

95 'ClickHouseDsn', 

96 'SnowflakeDsn', 

97] 

98 

99 

100@_dataclasses.dataclass 1gabhijkcdlmnoefpqr

101class UrlConstraints: 1gabhijkcdlmnoefpqr

102 """Url constraints. 

103 

104 Attributes: 

105 max_length: The maximum length of the url. Defaults to `None`. 

106 allowed_schemes: The allowed schemes. Defaults to `None`. 

107 host_required: Whether the host is required. Defaults to `None`. 

108 default_host: The default host. Defaults to `None`. 

109 default_port: The default port. Defaults to `None`. 

110 default_path: The default path. Defaults to `None`. 

111 preserve_empty_path: Whether to preserve empty URL paths. Defaults to `None`. 

112 """ 

113 

114 max_length: int | None = None 1gabhijkcdlmnoefpqr

115 allowed_schemes: list[str] | None = None 1gabhijkcdlmnoefpqr

116 host_required: bool | None = None 1gabhijkcdlmnoefpqr

117 default_host: str | None = None 1gabhijkcdlmnoefpqr

118 default_port: int | None = None 1gabhijkcdlmnoefpqr

119 default_path: str | None = None 1gabhijkcdlmnoefpqr

120 preserve_empty_path: bool | None = None 1gabhijkcdlmnoefpqr

121 

122 def __hash__(self) -> int: 1gabhijkcdlmnoefpqr

123 return hash( 1gabhijkcdlmnoefpqr

124 ( 

125 self.max_length, 

126 tuple(self.allowed_schemes) if self.allowed_schemes is not None else None, 

127 self.host_required, 

128 self.default_host, 

129 self.default_port, 

130 self.default_path, 

131 self.preserve_empty_path, 

132 ) 

133 ) 

134 

135 @property 1gabhijkcdlmnoefpqr

136 def defined_constraints(self) -> dict[str, Any]: 1gabhijkcdlmnoefpqr

137 """Fetch a key / value mapping of constraints to values that are not None. Used for core schema updates.""" 

138 return {field.name: value for field in fields(self) if (value := getattr(self, field.name)) is not None} 1gabhijkcdlmnoefpqr

139 

140 def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1gabhijkcdlmnoefpqr

141 schema = handler(source) 1gabhijkcdlmnoefpqr

142 

143 # for function-wrap schemas, url constraints is applied to the inner schema 

144 # because when we generate schemas for urls, we wrap a core_schema.url_schema() with a function-wrap schema 

145 # that helps with validation on initialization, see _BaseUrl and _BaseMultiHostUrl below. 

146 schema_to_mutate = schema['schema'] if schema['type'] == 'function-wrap' else schema 1gabhijkcdlmnoefpqr

147 if (annotated_type := schema_to_mutate['type']) not in ('url', 'multi-host-url'): 1gabhijkcdlmnoefpqr

148 raise PydanticUserError( 1gabhijkcdlmnoefpqr

149 f"'UrlConstraints' cannot annotate '{annotated_type}'.", code='invalid-annotated-type' 

150 ) 

151 for constraint_key, constraint_value in self.defined_constraints.items(): 1gabhijkcdlmnoefpqr

152 schema_to_mutate[constraint_key] = constraint_value 1gabhijkcdlmnoefpqr

153 return schema 1gabhijkcdlmnoefpqr

154 

155 

156class _BaseUrl: 1gabhijkcdlmnoefpqr

157 _constraints: ClassVar[UrlConstraints] = UrlConstraints() 1gabhijkcdlmnoefpqr

158 _url: _CoreUrl 1gabhijkcdlmnoefpqr

159 

160 def __init__(self, url: str | _CoreUrl | _BaseUrl) -> None: 1gabhijkcdlmnoefpqr

161 self._url = _build_type_adapter(self.__class__).validate_python(url)._url 1gabhijkcdlmnoefpqr

162 

163 @property 1gabhijkcdlmnoefpqr

164 def scheme(self) -> str: 1gabhijkcdlmnoefpqr

165 """The scheme part of the URL. 

166 

167 e.g. `https` in `https://user:pass@host:port/path?query#fragment` 

168 """ 

169 return self._url.scheme 1gabhijkcdlmnoefpqr

170 

171 @property 1gabhijkcdlmnoefpqr

172 def username(self) -> str | None: 1gabhijkcdlmnoefpqr

173 """The username part of the URL, or `None`. 

174 

175 e.g. `user` in `https://user:pass@host:port/path?query#fragment` 

176 """ 

177 return self._url.username 1gabhijkcdlmnoefpqr

178 

179 @property 1gabhijkcdlmnoefpqr

180 def password(self) -> str | None: 1gabhijkcdlmnoefpqr

181 """The password part of the URL, or `None`. 

182 

183 e.g. `pass` in `https://user:pass@host:port/path?query#fragment` 

184 """ 

185 return self._url.password 1gabhijkcdlmnoefpqr

186 

187 @property 1gabhijkcdlmnoefpqr

188 def host(self) -> str | None: 1gabhijkcdlmnoefpqr

189 """The host part of the URL, or `None`. 

190 

191 If the URL must be punycode encoded, this is the encoded host, e.g. if the input URL is `https://£££.com`, 

192 `host` will be `xn--9aaa.com` 

193 """ 

194 return self._url.host 1gabhijkcdlmnoefpqr

195 

196 def unicode_host(self) -> str | None: 1gabhijkcdlmnoefpqr

197 """The host part of the URL as a unicode string, or `None`. 

198 

199 e.g. `host` in `https://user:pass@host:port/path?query#fragment` 

200 

201 If the URL must be punycode encoded, this is the decoded host, e.g. if the input URL is `https://£££.com`, 

202 `unicode_host()` will be `£££.com` 

203 """ 

204 return self._url.unicode_host() 

205 

206 @property 1gabhijkcdlmnoefpqr

207 def port(self) -> int | None: 1gabhijkcdlmnoefpqr

208 """The port part of the URL, or `None`. 

209 

210 e.g. `port` in `https://user:pass@host:port/path?query#fragment` 

211 """ 

212 return self._url.port 1gabhijkcdlmnoefpqr

213 

214 @property 1gabhijkcdlmnoefpqr

215 def path(self) -> str | None: 1gabhijkcdlmnoefpqr

216 """The path part of the URL, or `None`. 

217 

218 e.g. `/path` in `https://user:pass@host:port/path?query#fragment` 

219 """ 

220 return self._url.path 1gabhijkcdlmnoefpqr

221 

222 @property 1gabhijkcdlmnoefpqr

223 def query(self) -> str | None: 1gabhijkcdlmnoefpqr

224 """The query part of the URL, or `None`. 

225 

226 e.g. `query` in `https://user:pass@host:port/path?query#fragment` 

227 """ 

228 return self._url.query 1gabhijkcdlmnoefpqr

229 

230 def query_params(self) -> list[tuple[str, str]]: 1gabhijkcdlmnoefpqr

231 """The query part of the URL as a list of key-value pairs. 

232 

233 e.g. `[('foo', 'bar')]` in `https://user:pass@host:port/path?foo=bar#fragment` 

234 """ 

235 return self._url.query_params() 

236 

237 @property 1gabhijkcdlmnoefpqr

238 def fragment(self) -> str | None: 1gabhijkcdlmnoefpqr

239 """The fragment part of the URL, or `None`. 

240 

241 e.g. `fragment` in `https://user:pass@host:port/path?query#fragment` 

242 """ 

243 return self._url.fragment 1gabhijkcdlmnoefpqr

244 

245 def unicode_string(self) -> str: 1gabhijkcdlmnoefpqr

246 """The URL as a unicode string, unlike `__str__()` this will not punycode encode the host. 

247 

248 If the URL must be punycode encoded, this is the decoded string, e.g. if the input URL is `https://£££.com`, 

249 `unicode_string()` will be `https://£££.com` 

250 """ 

251 return self._url.unicode_string() 1gabhijkcdlmnoefpqr

252 

253 def encoded_string(self) -> str: 1gabhijkcdlmnoefpqr

254 """The URL's encoded string representation via __str__(). 

255 

256 This returns the punycode-encoded host version of the URL as a string. 

257 """ 

258 return str(self) 1gabhijkcdlmnoefpqr

259 

260 def __str__(self) -> str: 1gabhijkcdlmnoefpqr

261 """The URL as a string, this will punycode encode the host if required.""" 

262 return str(self._url) 1gabhijkcdlmnoefpqr

263 

264 def __repr__(self) -> str: 1gabhijkcdlmnoefpqr

265 return f'{self.__class__.__name__}({str(self._url)!r})' 1gabhijkcdlmnoefpqr

266 

267 def __deepcopy__(self, memo: dict) -> Self: 1gabhijkcdlmnoefpqr

268 return self.__class__(self._url) 

269 

270 def __eq__(self, other: Any) -> bool: 1gabhijkcdlmnoefpqr

271 if self.__class__ is not other.__class__: 1gabhijkcdlmnoefpqr

272 return NotImplemented 1gabhijkcdlmnoefpqr

273 return self._url == other._url 1gabhijkcdlmnoefpqr

274 

275 def __lt__(self, other: Any) -> bool: 1gabhijkcdlmnoefpqr

276 if self.__class__ is not other.__class__: 1gabhijkcdlmnoefpqr

277 return NotImplemented 1gabhijkcdlmnoefpqr

278 return self._url < other._url 1gabhijkcdlmnoefpqr

279 

280 def __gt__(self, other: Any) -> bool: 1gabhijkcdlmnoefpqr

281 if self.__class__ is not other.__class__: 1gabhijkcdlmnoefpqr

282 return NotImplemented 1gabhijkcdlmnoefpqr

283 return self._url > other._url 1gabhijkcdlmnoefpqr

284 

285 def __le__(self, other: Any) -> bool: 1gabhijkcdlmnoefpqr

286 if self.__class__ is not other.__class__: 1gabhijkcdlmnoefpqr

287 return NotImplemented 1gabhijkcdlmnoefpqr

288 return self._url <= other._url 1gabhijkcdlmnoefpqr

289 

290 def __ge__(self, other: Any) -> bool: 1gabhijkcdlmnoefpqr

291 if self.__class__ is not other.__class__: 1gabhijkcdlmnoefpqr

292 return NotImplemented 1gabhijkcdlmnoefpqr

293 return self._url >= other._url 1gabhijkcdlmnoefpqr

294 

295 def __hash__(self) -> int: 1gabhijkcdlmnoefpqr

296 return hash(self._url) 1gabhijkcdlmnoefpqr

297 

298 def __len__(self) -> int: 1gabhijkcdlmnoefpqr

299 return len(str(self._url)) 1gabhijkcdlmnoefpqr

300 

301 @classmethod 1gabhijkcdlmnoefpqr

302 def build( 1gabhijkcdlmnoefpqr

303 cls, 

304 *, 

305 scheme: str, 

306 username: str | None = None, 

307 password: str | None = None, 

308 host: str, 

309 port: int | None = None, 

310 path: str | None = None, 

311 query: str | None = None, 

312 fragment: str | None = None, 

313 ) -> Self: 

314 """Build a new `Url` instance from its component parts. 

315 

316 Args: 

317 scheme: The scheme part of the URL. 

318 username: The username part of the URL, or omit for no username. 

319 password: The password part of the URL, or omit for no password. 

320 host: The host part of the URL. 

321 port: The port part of the URL, or omit for no port. 

322 path: The path part of the URL, or omit for no path. 

323 query: The query part of the URL, or omit for no query. 

324 fragment: The fragment part of the URL, or omit for no fragment. 

325 

326 Returns: 

327 An instance of URL 

328 """ 

329 return cls( 

330 _CoreUrl.build( 

331 scheme=scheme, 

332 username=username, 

333 password=password, 

334 host=host, 

335 port=port, 

336 path=path, 

337 query=query, 

338 fragment=fragment, 

339 ) 

340 ) 

341 

342 @classmethod 1gabhijkcdlmnoefpqr

343 def serialize_url(cls, url: Any, info: core_schema.SerializationInfo) -> str | Self: 1gabhijkcdlmnoefpqr

344 if not isinstance(url, cls): 1gabhijkcdlmnoefpqr

345 raise PydanticSerializationUnexpectedValue( 1gabhijkcdlmnoefpqr

346 f"Expected `{cls}` but got `{type(url)}` with value `'{url}'` - serialized value may not be as expected." 

347 ) 

348 if info.mode == 'json': 1gabhijkcdlmnoefpqr

349 return str(url) 1gabhijkcdlmnoefpqr

350 return url 1gabhijkcdlmnoefpqr

351 

352 @classmethod 1gabhijkcdlmnoefpqr

353 def __get_pydantic_core_schema__( 1gabhijkcdlmnoefpqr

354 cls, source: type[_BaseUrl], handler: GetCoreSchemaHandler 

355 ) -> core_schema.CoreSchema: 

356 def wrap_val(v, h): 1gabhijkcdlmnoefpqr

357 if isinstance(v, source): 1gabhijkcdlmnoefpqr

358 return v 1gabhijkcdlmnoefpqr

359 if isinstance(v, _BaseUrl): 359 ↛ 360line 359 didn't jump to line 360 because the condition on line 359 was never true1gabhijkcdlmnoefpqr

360 v = str(v) 

361 core_url = h(v) 1gabhijkcdlmnoefpqr

362 instance = source.__new__(source) 1gabhijkcdlmnoefpqr

363 instance._url = core_url 1gabhijkcdlmnoefpqr

364 return instance 1gabhijkcdlmnoefpqr

365 

366 return core_schema.no_info_wrap_validator_function( 1gabhijkcdlmnoefpqr

367 wrap_val, 

368 schema=core_schema.url_schema(**cls._constraints.defined_constraints), 

369 serialization=core_schema.plain_serializer_function_ser_schema( 

370 cls.serialize_url, info_arg=True, when_used='always' 

371 ), 

372 ) 

373 

374 @classmethod 1gabhijkcdlmnoefpqr

375 def __get_pydantic_json_schema__( 1gabhijkcdlmnoefpqr

376 cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler 

377 ) -> JsonSchemaValue: 

378 # we use the url schema for json schema generation, but we might have to extract it from 

379 # the function-wrap schema we use as a tool for validation on initialization 

380 inner_schema = core_schema['schema'] if core_schema['type'] == 'function-wrap' else core_schema 1gabhijkcdlmnoefpqr

381 return handler(inner_schema) 1gabhijkcdlmnoefpqr

382 

383 __pydantic_serializer__ = SchemaSerializer(core_schema.any_schema(serialization=core_schema.to_string_ser_schema())) 1gabhijkcdlmnoefpqr

384 

385 

386class _BaseMultiHostUrl: 1gabhijkcdlmnoefpqr

387 _constraints: ClassVar[UrlConstraints] = UrlConstraints() 1gabhijkcdlmnoefpqr

388 _url: _CoreMultiHostUrl 1gabhijkcdlmnoefpqr

389 

390 def __init__(self, url: str | _CoreMultiHostUrl | _BaseMultiHostUrl) -> None: 1gabhijkcdlmnoefpqr

391 self._url = _build_type_adapter(self.__class__).validate_python(url)._url 1gabhijkcdlmnoefpqr

392 

393 @property 1gabhijkcdlmnoefpqr

394 def scheme(self) -> str: 1gabhijkcdlmnoefpqr

395 """The scheme part of the URL. 

396 

397 e.g. `https` in `https://foo.com,bar.com/path?query#fragment` 

398 """ 

399 return self._url.scheme 1gabhijkcdlmnoefpqr

400 

401 @property 1gabhijkcdlmnoefpqr

402 def path(self) -> str | None: 1gabhijkcdlmnoefpqr

403 """The path part of the URL, or `None`. 

404 

405 e.g. `/path` in `https://foo.com,bar.com/path?query#fragment` 

406 """ 

407 return self._url.path 1gabhijkcdlmnoefpqr

408 

409 @property 1gabhijkcdlmnoefpqr

410 def query(self) -> str | None: 1gabhijkcdlmnoefpqr

411 """The query part of the URL, or `None`. 

412 

413 e.g. `query` in `https://foo.com,bar.com/path?query#fragment` 

414 """ 

415 return self._url.query 

416 

417 def query_params(self) -> list[tuple[str, str]]: 1gabhijkcdlmnoefpqr

418 """The query part of the URL as a list of key-value pairs. 

419 

420 e.g. `[('foo', 'bar')]` in `https://foo.com,bar.com/path?foo=bar#fragment` 

421 """ 

422 return self._url.query_params() 

423 

424 @property 1gabhijkcdlmnoefpqr

425 def fragment(self) -> str | None: 1gabhijkcdlmnoefpqr

426 """The fragment part of the URL, or `None`. 

427 

428 e.g. `fragment` in `https://foo.com,bar.com/path?query#fragment` 

429 """ 

430 return self._url.fragment 

431 

432 def hosts(self) -> list[MultiHostHost]: 1gabhijkcdlmnoefpqr

433 '''The hosts of the `MultiHostUrl` as [`MultiHostHost`][pydantic_core.MultiHostHost] typed dicts. 

434 

435 ```python 

436 from pydantic_core import MultiHostUrl 

437 

438 mhu = MultiHostUrl('https://foo.com:123,foo:bar@bar.com/path') 

439 print(mhu.hosts()) 

440 """ 

441 [ 

442 {'username': None, 'password': None, 'host': 'foo.com', 'port': 123}, 

443 {'username': 'foo', 'password': 'bar', 'host': 'bar.com', 'port': 443} 

444 ] 

445 ``` 

446 Returns: 

447 A list of dicts, each representing a host. 

448 ''' 

449 return self._url.hosts() 1gabhijkcdlmnoefpqr

450 

451 def encoded_string(self) -> str: 1gabhijkcdlmnoefpqr

452 """The URL's encoded string representation via __str__(). 

453 

454 This returns the punycode-encoded host version of the URL as a string. 

455 """ 

456 return str(self) 1gabhijkcdlmnoefpqr

457 

458 def unicode_string(self) -> str: 1gabhijkcdlmnoefpqr

459 """The URL as a unicode string, unlike `__str__()` this will not punycode encode the hosts.""" 

460 return self._url.unicode_string() 

461 

462 def __str__(self) -> str: 1gabhijkcdlmnoefpqr

463 """The URL as a string, this will punycode encode the host if required.""" 

464 return str(self._url) 1gabhijkcdlmnoefpqr

465 

466 def __repr__(self) -> str: 1gabhijkcdlmnoefpqr

467 return f'{self.__class__.__name__}({str(self._url)!r})' 1gabhijkcdlmnoefpqr

468 

469 def __deepcopy__(self, memo: dict) -> Self: 1gabhijkcdlmnoefpqr

470 return self.__class__(self._url) 

471 

472 def __eq__(self, other: Any) -> bool: 1gabhijkcdlmnoefpqr

473 if self.__class__ is not other.__class__: 1gabhijkcdlmnoefpqr

474 return NotImplemented 1gabhijkcdlmnoefpqr

475 return self._url == other._url 1gabhijkcdlmnoefpqr

476 

477 def __hash__(self) -> int: 1gabhijkcdlmnoefpqr

478 return hash(self._url) 1gabhijkcdlmnoefpqr

479 

480 def __len__(self) -> int: 1gabhijkcdlmnoefpqr

481 return len(str(self._url)) 1gabhijkcdlmnoefpqr

482 

483 @classmethod 1gabhijkcdlmnoefpqr

484 @overload 1gabhijkcdlmnoefpqr

485 def build( 1gabhijkcdlmnoefpqr

486 cls, 

487 *, 

488 scheme: str, 1abcdef

489 hosts: list[MultiHostHost], 1abcdef

490 username: None = None, 1gabhijkcdlmnoefpqr

491 password: None = None, 1gabhijkcdlmnoefpqr

492 host: None = None, 1gabhijkcdlmnoefpqr

493 port: None = None, 1gabhijkcdlmnoefpqr

494 path: str | None = None, 1gabhijkcdlmnoefpqr

495 query: str | None = None, 1gabhijkcdlmnoefpqr

496 fragment: str | None = None, 1gabhijkcdlmnoefpqr

497 ) -> Self: ... 1abcdef

498 @classmethod 1gabhijkcdlmnoefpqr

499 @overload 1gabhijkcdlmnoefpqr

500 def build( 1gabhijkcdlmnoefpqr

501 cls, 

502 *, 

503 scheme: str, 1abcdef

504 hosts: None = None, 1gabhijkcdlmnoefpqr

505 host: str, 1abcdef

506 username: str | None = None, 1gabhijkcdlmnoefpqr

507 password: str | None = None, 1gabhijkcdlmnoefpqr

508 port: int | None = None, 1gabhijkcdlmnoefpqr

509 path: str | None = None, 1gabhijkcdlmnoefpqr

510 query: str | None = None, 1gabhijkcdlmnoefpqr

511 fragment: str | None = None, 1gabhijkcdlmnoefpqr

512 ) -> Self: ... 1abcdef

513 @classmethod 1gabhijkcdlmnoefpqr

514 def build( 1gabhijkcdlmnoefpqr

515 cls, 

516 *, 

517 scheme: str, 

518 hosts: list[MultiHostHost] | None = None, 

519 username: str | None = None, 

520 password: str | None = None, 

521 host: str | None = None, 

522 port: int | None = None, 

523 path: str | None = None, 

524 query: str | None = None, 

525 fragment: str | None = None, 

526 ) -> Self: 

527 """Build a new `MultiHostUrl` instance from its component parts. 

528 

529 This method takes either `hosts` - a list of `MultiHostHost` typed dicts, or the individual components 

530 `username`, `password`, `host` and `port`. 

531 

532 Args: 

533 scheme: The scheme part of the URL. 

534 hosts: Multiple hosts to build the URL from. 

535 username: The username part of the URL. 

536 password: The password part of the URL. 

537 host: The host part of the URL. 

538 port: The port part of the URL. 

539 path: The path part of the URL. 

540 query: The query part of the URL, or omit for no query. 

541 fragment: The fragment part of the URL, or omit for no fragment. 

542 

543 Returns: 

544 An instance of `MultiHostUrl` 

545 """ 

546 return cls( 1gabhijkcdlmnoefpqr

547 _CoreMultiHostUrl.build( # pyright: ignore[reportCallIssue] 

548 scheme=scheme, 

549 hosts=hosts, # pyright: ignore[reportArgumentType] 

550 username=username, 

551 password=password, 

552 host=host, # pyright: ignore[reportArgumentType] 

553 port=port, 

554 path=path, 

555 query=query, 

556 fragment=fragment, 

557 ) 

558 ) 

559 

560 @classmethod 1gabhijkcdlmnoefpqr

561 def serialize_url(cls, url: Any, info: core_schema.SerializationInfo) -> str | Self: 1gabhijkcdlmnoefpqr

562 if not isinstance(url, cls): 

563 raise PydanticSerializationUnexpectedValue( 

564 f"Expected `{cls}` but got `{type(url)}` with value `'{url}'` - serialized value may not be as expected." 

565 ) 

566 if info.mode == 'json': 

567 return str(url) 

568 return url 

569 

570 @classmethod 1gabhijkcdlmnoefpqr

571 def __get_pydantic_core_schema__( 1gabhijkcdlmnoefpqr

572 cls, source: type[_BaseMultiHostUrl], handler: GetCoreSchemaHandler 

573 ) -> core_schema.CoreSchema: 

574 def wrap_val(v, h): 1gabhijkcdlmnoefpqr

575 if isinstance(v, source): 575 ↛ 576line 575 didn't jump to line 576 because the condition on line 575 was never true1gabhijkcdlmnoefpqr

576 return v 

577 if isinstance(v, _BaseMultiHostUrl): 577 ↛ 578line 577 didn't jump to line 578 because the condition on line 577 was never true1gabhijkcdlmnoefpqr

578 v = str(v) 

579 core_url = h(v) 1gabhijkcdlmnoefpqr

580 instance = source.__new__(source) 1gabhijkcdlmnoefpqr

581 instance._url = core_url 1gabhijkcdlmnoefpqr

582 return instance 1gabhijkcdlmnoefpqr

583 

584 return core_schema.no_info_wrap_validator_function( 1gabhijkcdlmnoefpqr

585 wrap_val, 

586 schema=core_schema.multi_host_url_schema(**cls._constraints.defined_constraints), 

587 serialization=core_schema.plain_serializer_function_ser_schema( 

588 cls.serialize_url, info_arg=True, when_used='always' 

589 ), 

590 ) 

591 

592 @classmethod 1gabhijkcdlmnoefpqr

593 def __get_pydantic_json_schema__( 1gabhijkcdlmnoefpqr

594 cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler 

595 ) -> JsonSchemaValue: 

596 # we use the url schema for json schema generation, but we might have to extract it from 

597 # the function-wrap schema we use as a tool for validation on initialization 

598 inner_schema = core_schema['schema'] if core_schema['type'] == 'function-wrap' else core_schema 

599 return handler(inner_schema) 

600 

601 __pydantic_serializer__ = SchemaSerializer(core_schema.any_schema(serialization=core_schema.to_string_ser_schema())) 1gabhijkcdlmnoefpqr

602 

603 

604@lru_cache 1gabhijkcdlmnoefpqr

605def _build_type_adapter(cls: type[_BaseUrl | _BaseMultiHostUrl]) -> TypeAdapter: 1gabhijkcdlmnoefpqr

606 return TypeAdapter(cls) 1gabhijkcdlmnoefpqr

607 

608 

609class AnyUrl(_BaseUrl): 1gabhijkcdlmnoefpqr

610 """Base type for all URLs. 

611 

612 * Any scheme allowed 

613 * Top-level domain (TLD) not required 

614 * Host not required 

615 

616 Assuming an input URL of `http://samuel:pass@example.com:8000/the/path/?query=here#fragment=is;this=bit`, 

617 the types export the following properties: 

618 

619 - `scheme`: the URL scheme (`http`), always set. 

620 - `host`: the URL host (`example.com`). 

621 - `username`: optional username if included (`samuel`). 

622 - `password`: optional password if included (`pass`). 

623 - `port`: optional port (`8000`). 

624 - `path`: optional path (`/the/path/`). 

625 - `query`: optional URL query (for example, `GET` arguments or "search string", such as `query=here`). 

626 - `fragment`: optional fragment (`fragment=is;this=bit`). 

627 """ 

628 

629 

630# Note: all single host urls inherit from `AnyUrl` to preserve compatibility with pre-v2.10 code 

631# Where urls were annotated variants of `AnyUrl`, which was an alias to `pydantic_core.Url` 

632 

633 

634class AnyHttpUrl(AnyUrl): 1gabhijkcdlmnoefpqr

635 """A type that will accept any http or https URL. 

636 

637 * TLD not required 

638 * Host not required 

639 """ 

640 

641 _constraints = UrlConstraints(allowed_schemes=['http', 'https']) 1gabhijkcdlmnoefpqr

642 

643 

644class HttpUrl(AnyUrl): 1gabhijkcdlmnoefpqr

645 """A type that will accept any http or https URL. 

646 

647 * TLD not required 

648 * Host not required 

649 * Max length 2083 

650 

651 ```python 

652 from pydantic import BaseModel, HttpUrl, ValidationError 

653 

654 class MyModel(BaseModel): 

655 url: HttpUrl 

656 

657 m = MyModel(url='http://www.example.com') # (1)! 

658 print(m.url) 

659 #> http://www.example.com/ 

660 

661 try: 

662 MyModel(url='ftp://invalid.url') 

663 except ValidationError as e: 

664 print(e) 

665 ''' 

666 1 validation error for MyModel 

667 url 

668 URL scheme should be 'http' or 'https' [type=url_scheme, input_value='ftp://invalid.url', input_type=str] 

669 ''' 

670 

671 try: 

672 MyModel(url='not a url') 

673 except ValidationError as e: 

674 print(e) 

675 ''' 

676 1 validation error for MyModel 

677 url 

678 Input should be a valid URL, relative URL without a base [type=url_parsing, input_value='not a url', input_type=str] 

679 ''' 

680 ``` 

681 

682 1. Note: mypy would prefer `m = MyModel(url=HttpUrl('http://www.example.com'))`, but Pydantic will convert the string to an HttpUrl instance anyway. 

683 

684 "International domains" (e.g. a URL where the host or TLD includes non-ascii characters) will be encoded via 

685 [punycode](https://en.wikipedia.org/wiki/Punycode) (see 

686 [this article](https://www.xudongz.com/blog/2017/idn-phishing/) for a good description of why this is important): 

687 

688 ```python 

689 from pydantic import BaseModel, HttpUrl 

690 

691 class MyModel(BaseModel): 

692 url: HttpUrl 

693 

694 m1 = MyModel(url='http://puny£code.com') 

695 print(m1.url) 

696 #> http://xn--punycode-eja.com/ 

697 m2 = MyModel(url='https://www.аррӏе.com/') 

698 print(m2.url) 

699 #> https://www.xn--80ak6aa92e.com/ 

700 m3 = MyModel(url='https://www.example.珠宝/') 

701 print(m3.url) 

702 #> https://www.example.xn--pbt977c/ 

703 ``` 

704 

705 

706 !!! warning "Underscores in Hostnames" 

707 In Pydantic, underscores are allowed in all parts of a domain except the TLD. 

708 Technically this might be wrong - in theory the hostname cannot have underscores, but subdomains can. 

709 

710 To explain this; consider the following two cases: 

711 

712 - `exam_ple.co.uk`: the hostname is `exam_ple`, which should not be allowed since it contains an underscore. 

713 - `foo_bar.example.com` the hostname is `example`, which should be allowed since the underscore is in the subdomain. 

714 

715 Without having an exhaustive list of TLDs, it would be impossible to differentiate between these two. Therefore 

716 underscores are allowed, but you can always do further validation in a validator if desired. 

717 

718 Also, Chrome, Firefox, and Safari all currently accept `http://exam_ple.com` as a URL, so we're in good 

719 (or at least big) company. 

720 """ 

721 

722 _constraints = UrlConstraints(max_length=2083, allowed_schemes=['http', 'https']) 1gabhijkcdlmnoefpqr

723 

724 

725class AnyWebsocketUrl(AnyUrl): 1gabhijkcdlmnoefpqr

726 """A type that will accept any ws or wss URL. 

727 

728 * TLD not required 

729 * Host not required 

730 """ 

731 

732 _constraints = UrlConstraints(allowed_schemes=['ws', 'wss']) 1gabhijkcdlmnoefpqr

733 

734 

735class WebsocketUrl(AnyUrl): 1gabhijkcdlmnoefpqr

736 """A type that will accept any ws or wss URL. 

737 

738 * TLD not required 

739 * Host not required 

740 * Max length 2083 

741 """ 

742 

743 _constraints = UrlConstraints(max_length=2083, allowed_schemes=['ws', 'wss']) 1gabhijkcdlmnoefpqr

744 

745 

746class FileUrl(AnyUrl): 1gabhijkcdlmnoefpqr

747 """A type that will accept any file URL. 

748 

749 * Host not required 

750 """ 

751 

752 _constraints = UrlConstraints(allowed_schemes=['file']) 1gabhijkcdlmnoefpqr

753 

754 

755class FtpUrl(AnyUrl): 1gabhijkcdlmnoefpqr

756 """A type that will accept ftp URL. 

757 

758 * TLD not required 

759 * Host not required 

760 """ 

761 

762 _constraints = UrlConstraints(allowed_schemes=['ftp']) 1gabhijkcdlmnoefpqr

763 

764 

765class PostgresDsn(_BaseMultiHostUrl): 1gabhijkcdlmnoefpqr

766 """A type that will accept any Postgres DSN. 

767 

768 * User info required 

769 * TLD not required 

770 * Host required 

771 * Supports multiple hosts 

772 

773 If further validation is required, these properties can be used by validators to enforce specific behaviour: 

774 

775 ```python 

776 from pydantic import ( 

777 BaseModel, 

778 HttpUrl, 

779 PostgresDsn, 

780 ValidationError, 

781 field_validator, 

782 ) 

783 

784 class MyModel(BaseModel): 

785 url: HttpUrl 

786 

787 m = MyModel(url='http://www.example.com') 

788 

789 # the repr() method for a url will display all properties of the url 

790 print(repr(m.url)) 

791 #> HttpUrl('http://www.example.com/') 

792 print(m.url.scheme) 

793 #> http 

794 print(m.url.host) 

795 #> www.example.com 

796 print(m.url.port) 

797 #> 80 

798 

799 class MyDatabaseModel(BaseModel): 

800 db: PostgresDsn 

801 

802 @field_validator('db') 

803 def check_db_name(cls, v): 

804 assert v.path and len(v.path) > 1, 'database must be provided' 

805 return v 

806 

807 m = MyDatabaseModel(db='postgres://user:pass@localhost:5432/foobar') 

808 print(m.db) 

809 #> postgres://user:pass@localhost:5432/foobar 

810 

811 try: 

812 MyDatabaseModel(db='postgres://user:pass@localhost:5432') 

813 except ValidationError as e: 

814 print(e) 

815 ''' 

816 1 validation error for MyDatabaseModel 

817 db 

818 Assertion failed, database must be provided 

819 assert (None) 

820 + where None = PostgresDsn('postgres://user:pass@localhost:5432').path [type=assertion_error, input_value='postgres://user:pass@localhost:5432', input_type=str] 

821 ''' 

822 ``` 

823 """ 

824 

825 _constraints = UrlConstraints( 1gabhijkcdlmnoefpqr

826 host_required=True, 

827 allowed_schemes=[ 

828 'postgres', 

829 'postgresql', 

830 'postgresql+asyncpg', 

831 'postgresql+pg8000', 

832 'postgresql+psycopg', 

833 'postgresql+psycopg2', 

834 'postgresql+psycopg2cffi', 

835 'postgresql+py-postgresql', 

836 'postgresql+pygresql', 

837 ], 

838 ) 

839 

840 @property 1gabhijkcdlmnoefpqr

841 def host(self) -> str: 1gabhijkcdlmnoefpqr

842 """The required URL host.""" 

843 return self._url.host # pyright: ignore[reportAttributeAccessIssue] 

844 

845 

846class CockroachDsn(AnyUrl): 1gabhijkcdlmnoefpqr

847 """A type that will accept any Cockroach DSN. 

848 

849 * User info required 

850 * TLD not required 

851 * Host required 

852 """ 

853 

854 _constraints = UrlConstraints( 1gabhijkcdlmnoefpqr

855 host_required=True, 

856 allowed_schemes=[ 

857 'cockroachdb', 

858 'cockroachdb+psycopg2', 

859 'cockroachdb+asyncpg', 

860 ], 

861 ) 

862 

863 @property 1gabhijkcdlmnoefpqr

864 def host(self) -> str: 1gabhijkcdlmnoefpqr

865 """The required URL host.""" 

866 return self._url.host # pyright: ignore[reportReturnType] 

867 

868 

869class AmqpDsn(AnyUrl): 1gabhijkcdlmnoefpqr

870 """A type that will accept any AMQP DSN. 

871 

872 * User info required 

873 * TLD not required 

874 * Host not required 

875 """ 

876 

877 _constraints = UrlConstraints(allowed_schemes=['amqp', 'amqps']) 1gabhijkcdlmnoefpqr

878 

879 

880class RedisDsn(AnyUrl): 1gabhijkcdlmnoefpqr

881 """A type that will accept any Redis DSN. 

882 

883 * User info required 

884 * TLD not required 

885 * Host required (e.g., `rediss://:pass@localhost`) 

886 """ 

887 

888 _constraints = UrlConstraints( 1gabhijkcdlmnoefpqr

889 allowed_schemes=['redis', 'rediss'], 

890 default_host='localhost', 

891 default_port=6379, 

892 default_path='/0', 

893 host_required=True, 

894 ) 

895 

896 @property 1gabhijkcdlmnoefpqr

897 def host(self) -> str: 1gabhijkcdlmnoefpqr

898 """The required URL host.""" 

899 return self._url.host # pyright: ignore[reportReturnType] 1gabhijkcdlmnoefpqr

900 

901 

902class MongoDsn(_BaseMultiHostUrl): 1gabhijkcdlmnoefpqr

903 """A type that will accept any MongoDB DSN. 

904 

905 * User info not required 

906 * Database name not required 

907 * Port not required 

908 * User info may be passed without user part (e.g., `mongodb://mongodb0.example.com:27017`). 

909 

910 !!! warning 

911 If a port isn't specified, the default MongoDB port `27017` will be used. If this behavior is 

912 undesirable, you can use the following: 

913 

914 ```python 

915 from typing import Annotated 

916 

917 from pydantic_core import MultiHostUrl 

918 

919 from pydantic import UrlConstraints 

920 

921 MongoDsnNoDefaultPort = Annotated[ 

922 MultiHostUrl, 

923 UrlConstraints(allowed_schemes=['mongodb', 'mongodb+srv']), 

924 ] 

925 ``` 

926 """ 

927 

928 _constraints = UrlConstraints(allowed_schemes=['mongodb', 'mongodb+srv'], default_port=27017) 1gabhijkcdlmnoefpqr

929 

930 

931class KafkaDsn(AnyUrl): 1gabhijkcdlmnoefpqr

932 """A type that will accept any Kafka DSN. 

933 

934 * User info required 

935 * TLD not required 

936 * Host not required 

937 """ 

938 

939 _constraints = UrlConstraints(allowed_schemes=['kafka'], default_host='localhost', default_port=9092) 1gabhijkcdlmnoefpqr

940 

941 

942class NatsDsn(_BaseMultiHostUrl): 1gabhijkcdlmnoefpqr

943 """A type that will accept any NATS DSN. 

944 

945 NATS is a connective technology built for the ever increasingly hyper-connected world. 

946 It is a single technology that enables applications to securely communicate across 

947 any combination of cloud vendors, on-premise, edge, web and mobile, and devices. 

948 More: https://nats.io 

949 """ 

950 

951 _constraints = UrlConstraints( 1gabhijkcdlmnoefpqr

952 allowed_schemes=['nats', 'tls', 'ws', 'wss'], default_host='localhost', default_port=4222 

953 ) 

954 

955 

956class MySQLDsn(AnyUrl): 1gabhijkcdlmnoefpqr

957 """A type that will accept any MySQL DSN. 

958 

959 * User info required 

960 * TLD not required 

961 * Host not required 

962 """ 

963 

964 _constraints = UrlConstraints( 1gabhijkcdlmnoefpqr

965 allowed_schemes=[ 

966 'mysql', 

967 'mysql+mysqlconnector', 

968 'mysql+aiomysql', 

969 'mysql+asyncmy', 

970 'mysql+mysqldb', 

971 'mysql+pymysql', 

972 'mysql+cymysql', 

973 'mysql+pyodbc', 

974 ], 

975 default_port=3306, 

976 host_required=True, 

977 ) 

978 

979 

980class MariaDBDsn(AnyUrl): 1gabhijkcdlmnoefpqr

981 """A type that will accept any MariaDB DSN. 

982 

983 * User info required 

984 * TLD not required 

985 * Host not required 

986 """ 

987 

988 _constraints = UrlConstraints( 1gabhijkcdlmnoefpqr

989 allowed_schemes=['mariadb', 'mariadb+mariadbconnector', 'mariadb+pymysql'], 

990 default_port=3306, 

991 ) 

992 

993 

994class ClickHouseDsn(AnyUrl): 1gabhijkcdlmnoefpqr

995 """A type that will accept any ClickHouse DSN. 

996 

997 * User info required 

998 * TLD not required 

999 * Host not required 

1000 """ 

1001 

1002 _constraints = UrlConstraints( 1gabhijkcdlmnoefpqr

1003 allowed_schemes=[ 

1004 'clickhouse+native', 

1005 'clickhouse+asynch', 

1006 'clickhouse+http', 

1007 'clickhouse', 

1008 'clickhouses', 

1009 'clickhousedb', 

1010 ], 

1011 default_host='localhost', 

1012 default_port=9000, 

1013 ) 

1014 

1015 

1016class SnowflakeDsn(AnyUrl): 1gabhijkcdlmnoefpqr

1017 """A type that will accept any Snowflake DSN. 

1018 

1019 * User info required 

1020 * TLD not required 

1021 * Host required 

1022 """ 

1023 

1024 _constraints = UrlConstraints( 1gabhijkcdlmnoefpqr

1025 allowed_schemes=['snowflake'], 

1026 host_required=True, 

1027 ) 

1028 

1029 @property 1gabhijkcdlmnoefpqr

1030 def host(self) -> str: 1gabhijkcdlmnoefpqr

1031 """The required URL host.""" 

1032 return self._url.host # pyright: ignore[reportReturnType] 

1033 

1034 

1035def import_email_validator() -> None: 1gabhijkcdlmnoefpqr

1036 global email_validator 

1037 try: 1gabhijkcdlmnoefpqr

1038 import email_validator 1gabhijkcdlmnoefpqr

1039 except ImportError as e: 1gabhijkcdlmnoefpqr

1040 raise ImportError("email-validator is not installed, run `pip install 'pydantic[email]'`") from e 1gabhijkcdlmnoefpqr

1041 if not version('email-validator').partition('.')[0] == '2': 1gabhijkcdlmnoefpqr

1042 raise ImportError('email-validator version >= 2.0 required, run pip install -U email-validator') 1gabhijkcdlmnoefpqr

1043 

1044 

1045if TYPE_CHECKING: 1gabhijkcdlmnoefpqr

1046 EmailStr = Annotated[str, ...] 

1047else: 

1048 

1049 class EmailStr: 1gabhijkcdlmnoefpqr

1050 """ 

1051 Info: 

1052 To use this type, you need to install the optional 

1053 [`email-validator`](https://github.com/JoshData/python-email-validator) package: 

1054 

1055 ```bash 

1056 pip install email-validator 

1057 ``` 

1058 

1059 Validate email addresses. 

1060 

1061 ```python 

1062 from pydantic import BaseModel, EmailStr 

1063 

1064 class Model(BaseModel): 

1065 email: EmailStr 

1066 

1067 print(Model(email='contact@mail.com')) 

1068 #> email='contact@mail.com' 

1069 ``` 

1070 """ # noqa: D212 

1071 

1072 @classmethod 1gabhijkcdlmnoefpqr

1073 def __get_pydantic_core_schema__( 1gabhijkcdlmnoefpqr

1074 cls, 

1075 _source: type[Any], 

1076 _handler: GetCoreSchemaHandler, 

1077 ) -> core_schema.CoreSchema: 

1078 import_email_validator() 1gabhijkcdlmnoefpqr

1079 return core_schema.no_info_after_validator_function(cls._validate, core_schema.str_schema()) 1gabhijkcdlmnoefpqr

1080 

1081 @classmethod 1gabhijkcdlmnoefpqr

1082 def __get_pydantic_json_schema__( 1gabhijkcdlmnoefpqr

1083 cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler 

1084 ) -> JsonSchemaValue: 

1085 field_schema = handler(core_schema) 1gabhijkcdlmnoefpqr

1086 field_schema.update(type='string', format='email') 1gabhijkcdlmnoefpqr

1087 return field_schema 1gabhijkcdlmnoefpqr

1088 

1089 @classmethod 1gabhijkcdlmnoefpqr

1090 def _validate(cls, input_value: str, /) -> str: 1gabhijkcdlmnoefpqr

1091 return validate_email(input_value)[1] 1gabhijkcdlmnoefpqr

1092 

1093 

1094class NameEmail(_repr.Representation): 1gabhijkcdlmnoefpqr

1095 """ 

1096 Info: 

1097 To use this type, you need to install the optional 

1098 [`email-validator`](https://github.com/JoshData/python-email-validator) package: 

1099 

1100 ```bash 

1101 pip install email-validator 

1102 ``` 

1103 

1104 Validate a name and email address combination, as specified by 

1105 [RFC 5322](https://datatracker.ietf.org/doc/html/rfc5322#section-3.4). 

1106 

1107 The `NameEmail` has two properties: `name` and `email`. 

1108 In case the `name` is not provided, it's inferred from the email address. 

1109 

1110 ```python 

1111 from pydantic import BaseModel, NameEmail 

1112 

1113 class User(BaseModel): 

1114 email: NameEmail 

1115 

1116 user = User(email='Fred Bloggs <fred.bloggs@example.com>') 

1117 print(user.email) 

1118 #> Fred Bloggs <fred.bloggs@example.com> 

1119 print(user.email.name) 

1120 #> Fred Bloggs 

1121 

1122 user = User(email='fred.bloggs@example.com') 

1123 print(user.email) 

1124 #> fred.bloggs <fred.bloggs@example.com> 

1125 print(user.email.name) 

1126 #> fred.bloggs 

1127 ``` 

1128 """ # noqa: D212 

1129 

1130 __slots__ = 'name', 'email' 1gabhijkcdlmnoefpqr

1131 

1132 def __init__(self, name: str, email: str): 1gabhijkcdlmnoefpqr

1133 self.name = name 1gabhijkcdlmnoefpqr

1134 self.email = email 1gabhijkcdlmnoefpqr

1135 

1136 def __eq__(self, other: Any) -> bool: 1gabhijkcdlmnoefpqr

1137 return isinstance(other, NameEmail) and (self.name, self.email) == (other.name, other.email) 1gabhijkcdlmnoefpqr

1138 

1139 @classmethod 1gabhijkcdlmnoefpqr

1140 def __get_pydantic_json_schema__( 1gabhijkcdlmnoefpqr

1141 cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler 

1142 ) -> JsonSchemaValue: 

1143 field_schema = handler(core_schema) 1gabhijkcdlmnoefpqr

1144 field_schema.update(type='string', format='name-email') 1gabhijkcdlmnoefpqr

1145 return field_schema 1gabhijkcdlmnoefpqr

1146 

1147 @classmethod 1gabhijkcdlmnoefpqr

1148 def __get_pydantic_core_schema__( 1gabhijkcdlmnoefpqr

1149 cls, 

1150 _source: type[Any], 

1151 _handler: GetCoreSchemaHandler, 

1152 ) -> core_schema.CoreSchema: 

1153 import_email_validator() 1gabhijkcdlmnoefpqr

1154 

1155 return core_schema.no_info_after_validator_function( 1gabhijkcdlmnoefpqr

1156 cls._validate, 

1157 core_schema.json_or_python_schema( 

1158 json_schema=core_schema.str_schema(), 

1159 python_schema=core_schema.union_schema( 

1160 [core_schema.is_instance_schema(cls), core_schema.str_schema()], 

1161 custom_error_type='name_email_type', 

1162 custom_error_message='Input is not a valid NameEmail', 

1163 ), 

1164 serialization=core_schema.to_string_ser_schema(), 

1165 ), 

1166 ) 

1167 

1168 @classmethod 1gabhijkcdlmnoefpqr

1169 def _validate(cls, input_value: Self | str, /) -> Self: 1gabhijkcdlmnoefpqr

1170 if isinstance(input_value, str): 1gabhijkcdlmnoefpqr

1171 name, email = validate_email(input_value) 1gabhijkcdlmnoefpqr

1172 return cls(name, email) 1gabhijkcdlmnoefpqr

1173 else: 

1174 return input_value 1gabhijkcdlmnoefpqr

1175 

1176 def __str__(self) -> str: 1gabhijkcdlmnoefpqr

1177 if '@' in self.name: 1gabhijkcdlmnoefpqr

1178 return f'"{self.name}" <{self.email}>' 1gabhijkcdlmnoefpqr

1179 

1180 return f'{self.name} <{self.email}>' 1gabhijkcdlmnoefpqr

1181 

1182 

1183IPvAnyAddressType: TypeAlias = 'IPv4Address | IPv6Address' 1gabhijkcdlmnoefpqr

1184IPvAnyInterfaceType: TypeAlias = 'IPv4Interface | IPv6Interface' 1gabhijkcdlmnoefpqr

1185IPvAnyNetworkType: TypeAlias = 'IPv4Network | IPv6Network' 1gabhijkcdlmnoefpqr

1186 

1187if TYPE_CHECKING: 1gabhijkcdlmnoefpqr

1188 IPvAnyAddress = IPvAnyAddressType 

1189 IPvAnyInterface = IPvAnyInterfaceType 

1190 IPvAnyNetwork = IPvAnyNetworkType 

1191else: 

1192 

1193 class IPvAnyAddress: 1gabhijkcdlmnoefpqr

1194 """Validate an IPv4 or IPv6 address. 

1195 

1196 ```python 

1197 from pydantic import BaseModel 

1198 from pydantic.networks import IPvAnyAddress 

1199 

1200 class IpModel(BaseModel): 

1201 ip: IPvAnyAddress 

1202 

1203 print(IpModel(ip='127.0.0.1')) 

1204 #> ip=IPv4Address('127.0.0.1') 

1205 

1206 try: 

1207 IpModel(ip='http://www.example.com') 

1208 except ValueError as e: 

1209 print(e.errors()) 

1210 ''' 

1211 [ 

1212 { 

1213 'type': 'ip_any_address', 

1214 'loc': ('ip',), 

1215 'msg': 'value is not a valid IPv4 or IPv6 address', 

1216 'input': 'http://www.example.com', 

1217 } 

1218 ] 

1219 ''' 

1220 ``` 

1221 """ 

1222 

1223 __slots__ = () 1gabhijkcdlmnoefpqr

1224 

1225 def __new__(cls, value: Any) -> IPvAnyAddressType: 1gabhijkcdlmnoefpqr

1226 """Validate an IPv4 or IPv6 address.""" 

1227 try: 1gabhijkcdlmnoefpqr

1228 return IPv4Address(value) 1gabhijkcdlmnoefpqr

1229 except ValueError: 1gabhijkcdlmnoefpqr

1230 pass 1gabhijkcdlmnoefpqr

1231 

1232 try: 1gabhijkcdlmnoefpqr

1233 return IPv6Address(value) 1gabhijkcdlmnoefpqr

1234 except ValueError: 1gabhijkcdlmnoefpqr

1235 raise PydanticCustomError('ip_any_address', 'value is not a valid IPv4 or IPv6 address') 1gabhijkcdlmnoefpqr

1236 

1237 @classmethod 1gabhijkcdlmnoefpqr

1238 def __get_pydantic_json_schema__( 1gabhijkcdlmnoefpqr

1239 cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler 

1240 ) -> JsonSchemaValue: 

1241 field_schema = {} 1gabhijkcdlmnoefpqr

1242 field_schema.update(type='string', format='ipvanyaddress') 1gabhijkcdlmnoefpqr

1243 return field_schema 1gabhijkcdlmnoefpqr

1244 

1245 @classmethod 1gabhijkcdlmnoefpqr

1246 def __get_pydantic_core_schema__( 1gabhijkcdlmnoefpqr

1247 cls, 

1248 _source: type[Any], 

1249 _handler: GetCoreSchemaHandler, 

1250 ) -> core_schema.CoreSchema: 

1251 return core_schema.no_info_plain_validator_function( 1gabhijkcdlmnoefpqr

1252 cls._validate, serialization=core_schema.to_string_ser_schema() 

1253 ) 

1254 

1255 @classmethod 1gabhijkcdlmnoefpqr

1256 def _validate(cls, input_value: Any, /) -> IPvAnyAddressType: 1gabhijkcdlmnoefpqr

1257 return cls(input_value) # type: ignore[return-value] 1gabhijkcdlmnoefpqr

1258 

1259 class IPvAnyInterface: 1gabhijkcdlmnoefpqr

1260 """Validate an IPv4 or IPv6 interface.""" 

1261 

1262 __slots__ = () 1gabhijkcdlmnoefpqr

1263 

1264 def __new__(cls, value: NetworkType) -> IPvAnyInterfaceType: 1gabhijkcdlmnoefpqr

1265 """Validate an IPv4 or IPv6 interface.""" 

1266 try: 1gabhijkcdlmnoefpqr

1267 return IPv4Interface(value) 1gabhijkcdlmnoefpqr

1268 except ValueError: 1gabhijkcdlmnoefpqr

1269 pass 1gabhijkcdlmnoefpqr

1270 

1271 try: 1gabhijkcdlmnoefpqr

1272 return IPv6Interface(value) 1gabhijkcdlmnoefpqr

1273 except ValueError: 1gabhijkcdlmnoefpqr

1274 raise PydanticCustomError('ip_any_interface', 'value is not a valid IPv4 or IPv6 interface') 1gabhijkcdlmnoefpqr

1275 

1276 @classmethod 1gabhijkcdlmnoefpqr

1277 def __get_pydantic_json_schema__( 1gabhijkcdlmnoefpqr

1278 cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler 

1279 ) -> JsonSchemaValue: 

1280 field_schema = {} 1gabhijkcdlmnoefpqr

1281 field_schema.update(type='string', format='ipvanyinterface') 1gabhijkcdlmnoefpqr

1282 return field_schema 1gabhijkcdlmnoefpqr

1283 

1284 @classmethod 1gabhijkcdlmnoefpqr

1285 def __get_pydantic_core_schema__( 1gabhijkcdlmnoefpqr

1286 cls, 

1287 _source: type[Any], 

1288 _handler: GetCoreSchemaHandler, 

1289 ) -> core_schema.CoreSchema: 

1290 return core_schema.no_info_plain_validator_function( 1gabhijkcdlmnoefpqr

1291 cls._validate, serialization=core_schema.to_string_ser_schema() 

1292 ) 

1293 

1294 @classmethod 1gabhijkcdlmnoefpqr

1295 def _validate(cls, input_value: NetworkType, /) -> IPvAnyInterfaceType: 1gabhijkcdlmnoefpqr

1296 return cls(input_value) # type: ignore[return-value] 1gabhijkcdlmnoefpqr

1297 

1298 class IPvAnyNetwork: 1gabhijkcdlmnoefpqr

1299 """Validate an IPv4 or IPv6 network.""" 

1300 

1301 __slots__ = () 1gabhijkcdlmnoefpqr

1302 

1303 def __new__(cls, value: NetworkType) -> IPvAnyNetworkType: 1gabhijkcdlmnoefpqr

1304 """Validate an IPv4 or IPv6 network.""" 

1305 # Assume IP Network is defined with a default value for `strict` argument. 

1306 # Define your own class if you want to specify network address check strictness. 

1307 try: 1gabhijkcdlmnoefpqr

1308 return IPv4Network(value) 1gabhijkcdlmnoefpqr

1309 except ValueError: 1gabhijkcdlmnoefpqr

1310 pass 1gabhijkcdlmnoefpqr

1311 

1312 try: 1gabhijkcdlmnoefpqr

1313 return IPv6Network(value) 1gabhijkcdlmnoefpqr

1314 except ValueError: 1gabhijkcdlmnoefpqr

1315 raise PydanticCustomError('ip_any_network', 'value is not a valid IPv4 or IPv6 network') 1gabhijkcdlmnoefpqr

1316 

1317 @classmethod 1gabhijkcdlmnoefpqr

1318 def __get_pydantic_json_schema__( 1gabhijkcdlmnoefpqr

1319 cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler 

1320 ) -> JsonSchemaValue: 

1321 field_schema = {} 1gabhijkcdlmnoefpqr

1322 field_schema.update(type='string', format='ipvanynetwork') 1gabhijkcdlmnoefpqr

1323 return field_schema 1gabhijkcdlmnoefpqr

1324 

1325 @classmethod 1gabhijkcdlmnoefpqr

1326 def __get_pydantic_core_schema__( 1gabhijkcdlmnoefpqr

1327 cls, 

1328 _source: type[Any], 

1329 _handler: GetCoreSchemaHandler, 

1330 ) -> core_schema.CoreSchema: 

1331 return core_schema.no_info_plain_validator_function( 1gabhijkcdlmnoefpqr

1332 cls._validate, serialization=core_schema.to_string_ser_schema() 

1333 ) 

1334 

1335 @classmethod 1gabhijkcdlmnoefpqr

1336 def _validate(cls, input_value: NetworkType, /) -> IPvAnyNetworkType: 1gabhijkcdlmnoefpqr

1337 return cls(input_value) # type: ignore[return-value] 1gabhijkcdlmnoefpqr

1338 

1339 

1340def _build_pretty_email_regex() -> re.Pattern[str]: 1gabhijkcdlmnoefpqr

1341 name_chars = r'[\w.!#$%&\'*+\-/=?^_`{|}~]' 1gabhijkcdlmnoefpqr

1342 unquoted_name_group = rf'((?:{name_chars}+\s+)*{name_chars}+)' 1gabhijkcdlmnoefpqr

1343 quoted_name_group = r'"((?:[^"]|\")+)"' 1gabhijkcdlmnoefpqr

1344 email_group = r'<(.+)>' 1gabhijkcdlmnoefpqr

1345 return re.compile(rf'\s*(?:{unquoted_name_group}|{quoted_name_group})?\s*{email_group}\s*') 1gabhijkcdlmnoefpqr

1346 

1347 

1348pretty_email_regex = _build_pretty_email_regex() 1gabhijkcdlmnoefpqr

1349 

1350MAX_EMAIL_LENGTH = 2048 1gabhijkcdlmnoefpqr

1351"""Maximum length for an email. 1gabhijkcdlmnoefpqr

1352A somewhat arbitrary but very generous number compared to what is allowed by most implementations. 

1353""" 

1354 

1355 

1356def validate_email(value: str) -> tuple[str, str]: 1gabhijkcdlmnoefpqr

1357 """Email address validation using [email-validator](https://pypi.org/project/email-validator/). 

1358 

1359 Returns: 

1360 A tuple containing the local part of the email (or the name for "pretty" email addresses) 

1361 and the normalized email. 

1362 

1363 Raises: 

1364 PydanticCustomError: If the email is invalid. 

1365 

1366 Note: 

1367 Note that: 

1368 

1369 * Raw IP address (literal) domain parts are not allowed. 

1370 * `"John Doe <local_part@domain.com>"` style "pretty" email addresses are processed. 

1371 * Spaces are striped from the beginning and end of addresses, but no error is raised. 

1372 """ 

1373 if email_validator is None: 1gabhijkcdlmnoefpqr

1374 import_email_validator() 1gabhijkcdlmnoefpqr

1375 

1376 if len(value) > MAX_EMAIL_LENGTH: 1gabhijkcdlmnoefpqr

1377 raise PydanticCustomError( 1gabhijkcdlmnoefpqr

1378 'value_error', 

1379 'value is not a valid email address: {reason}', 

1380 {'reason': f'Length must not exceed {MAX_EMAIL_LENGTH} characters'}, 

1381 ) 

1382 

1383 # Carriage returns and line feeds are only allowed in a header field body as part of "folding" 

1384 # (a CRLF immediately followed by whitespace), which is unfolded before the value is parsed 

1385 # (see https://www.rfc-editor.org/info/rfc5322/#section-2.2). A `NameEmail` is a standalone value 

1386 # rather than a folded header line, so any CR or LF is rejected. 

1387 if '\r' in value or '\n' in value: 1gabhijkcdlmnoefpqr

1388 raise PydanticCustomError( 1gabhijkcdlmnoefpqr

1389 'value_error', 

1390 'value is not a valid email address: {reason}', 

1391 {'reason': 'Carriage return and line feed characters are not allowed'}, 

1392 ) 

1393 

1394 m = pretty_email_regex.fullmatch(value) 1gabhijkcdlmnoefpqr

1395 name: str | None = None 1gabhijkcdlmnoefpqr

1396 if m: 1gabhijkcdlmnoefpqr

1397 unquoted_name, quoted_name, value = m.groups() 1gabhijkcdlmnoefpqr

1398 name = unquoted_name or quoted_name 1gabhijkcdlmnoefpqr

1399 

1400 email = value.strip() 1gabhijkcdlmnoefpqr

1401 

1402 try: 1gabhijkcdlmnoefpqr

1403 parts = email_validator.validate_email(email, check_deliverability=False) 1gabhijkcdlmnoefpqr

1404 except email_validator.EmailNotValidError as e: 1gabhijkcdlmnoefpqr

1405 raise PydanticCustomError( 1gabhijkcdlmnoefpqr

1406 'value_error', 'value is not a valid email address: {reason}', {'reason': str(e.args[0])} 

1407 ) from e 

1408 

1409 email = parts.normalized 1gabhijkcdlmnoefpqr

1410 assert email is not None 1gabhijkcdlmnoefpqr

1411 name = name or parts.local_part 1gabhijkcdlmnoefpqr

1412 return name, email 1gabhijkcdlmnoefpqr