|
55 | 55 | human_quote, |
56 | 56 | ) |
57 | 57 |
|
| 58 | +try: |
| 59 | + from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler |
| 60 | + from pydantic.json_schema import JsonSchemaValue |
| 61 | + from pydantic_core import core_schema |
| 62 | + |
| 63 | + HAS_PYDANTIC = True |
| 64 | +except ImportError: |
| 65 | + HAS_PYDANTIC = False |
| 66 | + |
| 67 | + |
58 | 68 | DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443, "ftp": 21} |
59 | 69 | USES_RELATIVE = frozenset(uses_relative) |
60 | 70 |
|
@@ -1480,6 +1490,39 @@ def human_repr(self) -> str: |
1480 | 1490 | netloc = make_netloc(user, password, host, self.explicit_port) |
1481 | 1491 | return unsplit_result(self._scheme, netloc, path, query_string, fragment) |
1482 | 1492 |
|
| 1493 | + if HAS_PYDANTIC: # pragma: no cover |
| 1494 | + # Borrowed from https://docs.pydantic.dev/latest/concepts/types/#handling-third-party-types |
| 1495 | + @classmethod |
| 1496 | + def __get_pydantic_json_schema__( |
| 1497 | + cls, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler |
| 1498 | + ) -> JsonSchemaValue: |
| 1499 | + field_schema: dict[str, Any] = {} |
| 1500 | + field_schema.update(type="string", format="uri") |
| 1501 | + return field_schema |
| 1502 | + |
| 1503 | + @classmethod |
| 1504 | + def __get_pydantic_core_schema__( |
| 1505 | + cls, source_type: type[Self] | type[str], handler: GetCoreSchemaHandler |
| 1506 | + ) -> core_schema.CoreSchema: |
| 1507 | + from_str_schema = core_schema.chain_schema( |
| 1508 | + [ |
| 1509 | + core_schema.str_schema(), |
| 1510 | + core_schema.no_info_plain_validator_function(URL), |
| 1511 | + ] |
| 1512 | + ) |
| 1513 | + |
| 1514 | + return core_schema.json_or_python_schema( |
| 1515 | + json_schema=from_str_schema, |
| 1516 | + python_schema=core_schema.union_schema( |
| 1517 | + [ |
| 1518 | + # check if it's an instance first before doing any further work |
| 1519 | + core_schema.is_instance_schema(URL), |
| 1520 | + from_str_schema, |
| 1521 | + ] |
| 1522 | + ), |
| 1523 | + serialization=core_schema.plain_serializer_function_ser_schema(str), |
| 1524 | + ) |
| 1525 | + |
1483 | 1526 |
|
1484 | 1527 | _DEFAULT_IDNA_SIZE = 256 |
1485 | 1528 | _DEFAULT_ENCODE_SIZE = 512 |
|
0 commit comments