Skip to content

Commit

Permalink
📝 Update docstings on networks.py (#6069)
Browse files Browse the repository at this point in the history
Co-authored-by: Terrence Dorsey <terrend@mishu.com>
  • Loading branch information
Kludex and tpdorsey committed Jun 9, 2023
1 parent 9de2787 commit 459b6c6
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 8 deletions.
45 changes: 38 additions & 7 deletions pydantic/networks.py
@@ -1,3 +1,4 @@
"""The networks module contains types for common network-related fields."""
from __future__ import annotations as _annotations

import dataclasses as _dataclasses
Expand Down Expand Up @@ -78,10 +79,13 @@ def __hash__(self) -> int:


AnyUrl = Url
# host_required is false because all schemes are "special" so host is required by rust-url automatically
"""Base type for all URLs."""
AnyHttpUrl = Annotated[Url, UrlConstraints(allowed_schemes=['http', 'https'])]
"""A type that will accept any http or https URL."""
HttpUrl = Annotated[Url, UrlConstraints(max_length=2083, allowed_schemes=['http', 'https'])]
"""A type that will accept any http or https URL with a max length of 2083 characters."""
FileUrl = Annotated[Url, UrlConstraints(allowed_schemes=['file'])]
"""A type that will accept any file URL."""
PostgresDsn = Annotated[
MultiHostUrl,
UrlConstraints(
Expand All @@ -99,6 +103,7 @@ def __hash__(self) -> int:
],
),
]
"""A type that will accept any Postgres DSN."""

CockroachDsn = Annotated[
Url,
Expand All @@ -111,13 +116,18 @@ def __hash__(self) -> int:
],
),
]
"""A type that will accept any Cockroach DSN."""
AmqpDsn = Annotated[Url, UrlConstraints(allowed_schemes=['amqp', 'amqps'])]
"""A type that will accept any AMQP DSN."""
RedisDsn = Annotated[
Url,
UrlConstraints(allowed_schemes=['redis', 'rediss'], default_host='localhost', default_port=6379, default_path='/0'),
]
"""A type that will accept any Redis DSN."""
MongoDsn = Annotated[MultiHostUrl, UrlConstraints(allowed_schemes=['mongodb', 'mongodb+srv'], default_port=27017)]
"""A type that will accept any MongoDB DSN."""
KafkaDsn = Annotated[Url, UrlConstraints(allowed_schemes=['kafka'], default_host='localhost', default_port=9092)]
"""A type that will accept any Kafka DSN."""
MySQLDsn = Annotated[
Url,
UrlConstraints(
Expand All @@ -134,13 +144,15 @@ def __hash__(self) -> int:
default_port=3306,
),
]
"""A type that will accept any MySQL DSN."""
MariaDBDsn = Annotated[
Url,
UrlConstraints(
allowed_schemes=['mariadb', 'mariadb+mariadbconnector', 'mariadb+pymysql'],
default_port=3306,
),
]
"""A type that will accept any MariaDB DSN."""


def import_email_validator() -> None:
Expand All @@ -156,13 +168,27 @@ def import_email_validator() -> None:
else:

class EmailStr:
"""Validate email addresses.
Example:
```py
from pydantic import BaseModel, EmailStr
class Model(BaseModel):
email: EmailStr
print(Model(email='contact@mail.com'))
# > email='contact@mail.com'
```
"""

@classmethod
def __get_pydantic_core_schema__(
cls,
source: type[Any],
) -> core_schema.CoreSchema:
import_email_validator()
return core_schema.general_after_validator_function(cls.validate, core_schema.str_schema())
return core_schema.general_after_validator_function(cls._validate, core_schema.str_schema())

@classmethod
def __get_pydantic_json_schema__(
Expand All @@ -173,7 +199,7 @@ def __get_pydantic_json_schema__(
return field_schema

@classmethod
def validate(cls, __input_value: str, _: core_schema.ValidationInfo) -> str:
def _validate(cls, __input_value: str, _: core_schema.ValidationInfo) -> str:
return validate_email(__input_value)[1]


Expand Down Expand Up @@ -243,6 +269,7 @@ class IPvAnyAddress:
__slots__ = ()

def __new__(cls, value: Any) -> IPv4Address | IPv6Address: # type: ignore[misc]
"""Validate an IPv4 or IPv6 address."""
try:
return IPv4Address(value)
except ValueError:
Expand Down Expand Up @@ -279,6 +306,7 @@ class IPvAnyInterface:
__slots__ = ()

def __new__(cls, value: NetworkType) -> IPv4Interface | IPv6Interface: # type: ignore[misc]
"""Validate an IPv4 or IPv6 interface."""
try:
return IPv4Interface(value)
except ValueError:
Expand Down Expand Up @@ -315,6 +343,7 @@ class IPvAnyNetwork:
__slots__ = ()

def __new__(cls, value: NetworkType) -> IPv4Network | IPv6Network: # type: ignore[misc]
"""Validate an IPv4 or IPv6 network."""
# Assume IP Network is defined with a default value for `strict` argument.
# Define your own class if you want to specify network address check strictness.
try:
Expand Down Expand Up @@ -353,10 +382,12 @@ def _validate(cls, __input_value: NetworkType, _: core_schema.ValidationInfo) ->
def validate_email(value: str) -> tuple[str, str]:
"""Email address validation using https://pypi.org/project/email-validator/.
Notes:
* raw ip address (literal) domain parts are not allowed.
* "John Doe <local_part@domain.com>" style "pretty" email addresses are processed
* spaces are striped from the beginning and end of addresses but no error is raised
Note:
Note that:
* Raw IP address (literal) domain parts are not allowed.
* "John Doe <local_part@domain.com>" style "pretty" email addresses are processed.
* Spaces are striped from the beginning and end of addresses, but no error is raised.
"""
if email_validator is None:
import_email_validator()
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Expand Up @@ -182,7 +182,6 @@ convention = "google"
'pydantic/json_schema.py' = ['D']
'pydantic/main.py' = ['D']
'pydantic/mypy.py' = ['D']
'pydantic/networks.py' = ['D']
'pydantic/root_model.py' = ['D']
'pydantic/type_adapter.py' = ['D']
'pydantic/types.py' = ['D']
Expand Down

0 comments on commit 459b6c6

Please sign in to comment.