Skip to content
You're viewing docs for v2.8. See the latest version →

Network Types

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

GetCoreSchemaHandler

Handler to call into the next CoreSchema schema generation function.

Attributes

field_name

Get the name of the closest field to this validator.

Type: str | None

Methods

call

def __call__(source_type: Any) -> core_schema.CoreSchema

Call the inner handler and get the CoreSchema it returns. This will call the next CoreSchema modifying function up until it calls into Pydantic’s internal schema generation machinery, which will raise a pydantic.errors.PydanticSchemaGenerationError error if it cannot generate a CoreSchema for the given source type.

Returns

core_schema.CoreSchema — The pydantic-core CoreSchema generated.

Parameters

source_type : Any

The input type.

generate_schema

def generate_schema(source_type: Any) -> core_schema.CoreSchema

Generate a schema unrelated to the current context. Use this function if e.g. you are handling schema generation for a sequence and want to generate a schema for its items. Otherwise, you may end up doing something like applying a min_length constraint that was intended for the sequence itself to its items!

Returns

core_schema.CoreSchema — The pydantic-core CoreSchema generated.

Parameters

source_type : Any

The input type.

resolve_ref_schema

def resolve_ref_schema(
    maybe_ref_schema: core_schema.CoreSchema,
) -> core_schema.CoreSchema

Get the real schema for a definition-ref schema. If the schema given is not a definition-ref schema, it will be returned as is. This means you don’t have to check before calling this function.

Returns

core_schema.CoreSchema — A concrete CoreSchema.

Parameters

maybe_ref_schema : core_schema.CoreSchema

A CoreSchema, ref-based or not.

Raises
  • LookupError — If the ref is not found.

UrlConstraints

Bases: PydanticMetadata

Url constraints.

Attributes

max_length

Type: int | None Default: None

allowed_schemes

Type: list[str] | None Default: None

host_required

Type: bool | None Default: None

default_host

Type: str | None Default: None

default_port

Type: int | None Default: None

default_path

Type: str | None Default: None


EmailStr

Validate email addresses.

from pydantic import BaseModel, EmailStr

class Model(BaseModel):
    email: EmailStr

print(Model(email='[email protected]'))
#> email='[email protected]'

NameEmail

Bases: Representation

Validate a name and email address combination, as specified by RFC 5322.

The NameEmail has two properties: name and email. In case the name is not provided, it’s inferred from the email address.

from pydantic import BaseModel, NameEmail

class User(BaseModel):
    email: NameEmail

user = User(email='Fred Bloggs <[email protected]>')
print(user.email)
#> Fred Bloggs <[email protected]>
print(user.email.name)
#> Fred Bloggs

user = User(email='[email protected]')
print(user.email)
#> fred.bloggs <[email protected]>
print(user.email.name)
#> fred.bloggs

Attributes

name

Default: name

email

Default: email


IPvAnyAddress

Validate an IPv4 or IPv6 address.

from pydantic import BaseModel
from pydantic.networks import IPvAnyAddress

class IpModel(BaseModel):
    ip: IPvAnyAddress

print(IpModel(ip='127.0.0.1'))
#> ip=IPv4Address('127.0.0.1')

try:
    IpModel(ip='http://www.example.com')
except ValueError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'ip_any_address',
            'loc': ('ip',),
            'msg': 'value is not a valid IPv4 or IPv6 address',
            'input': 'http://www.example.com',
        }
    ]
    '''

Methods

new

def __new__(cls, value: Any) -> IPv4Address | IPv6Address

Validate an IPv4 or IPv6 address.

Returns

IPv4Address | IPv6Address


IPvAnyInterface

Validate an IPv4 or IPv6 interface.

Methods

new

def __new__(cls, value: NetworkType) -> IPv4Interface | IPv6Interface

Validate an IPv4 or IPv6 interface.

Returns

IPv4Interface | IPv6Interface


IPvAnyNetwork

Validate an IPv4 or IPv6 network.

Methods

new

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

Validate an IPv4 or IPv6 network.

Returns

IPvAnyNetworkType


getattr_migration

def getattr_migration(module: str) -> Callable[[str], Any]

Implement PEP 562 for objects that were either moved or removed on the migration to V2.

Returns

Callable[[str], Any] — A callable that will raise an error if the object is not found.

Parameters

module : str

The module name.


import_email_validator

def import_email_validator() -> None

Returns

None


validate_email

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

Email address validation using email-validator.

Returns

tuple[str, str]


JsonSchemaValue

A type alias for a JSON schema value. This is a dictionary of string keys to arbitrary JSON values.

Default: Dict[str, Any]

NetworkType

Type: TypeAlias Default: 'str | bytes | int | tuple[str | bytes | int, str | int]'

AnyUrl

Base type for all URLs.

  • Any scheme allowed
  • Top-level domain (TLD) not required
  • Host required

Assuming an input URL of http://samuel:[email protected]:8000/the/path/?query=here#fragment=is;this=bit, the types export the following properties:

  • scheme: the URL scheme (http), always set.
  • host: the URL host (example.com), always set.
  • username: optional username if included (samuel).
  • password: optional password if included (pass).
  • port: optional port (8000).
  • path: optional path (/the/path/).
  • query: optional URL query (for example, GET arguments or “search string”, such as query=here).
  • fragment: optional fragment (fragment=is;this=bit).

Default: Url

AnyHttpUrl

A type that will accept any http or https URL.

  • TLD not required
  • Host required

Default: Annotated[Url, UrlConstraints(allowed_schemes=['http', 'https'])]

HttpUrl

A type that will accept any http or https URL.

  • TLD not required
  • Host required
  • Max length 2083
from pydantic import BaseModel, HttpUrl, ValidationError

class MyModel(BaseModel):
  url: HttpUrl

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

try:
  MyModel(url='ftp://invalid.url')
except ValidationError as e:
  print(e)
  '''
  1 validation error for MyModel
  url
    URL scheme should be 'http' or 'https' [type=url_scheme, input_value='ftp://invalid.url', input_type=str]
  '''

try:
  MyModel(url='not a url')
except ValidationError as e:
  print(e)
  '''
  1 validation error for MyModel
  url
    Input should be a valid URL, relative URL without a base [type=url_parsing, input_value='not a url', input_type=str]
  '''

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

“International domains” (e.g. a URL where the host or TLD includes non-ascii characters) will be encoded via punycode (see this article for a good description of why this is important):

from pydantic import BaseModel, HttpUrl

class MyModel(BaseModel):
    url: HttpUrl

m1 = MyModel(url='http://puny£code.com')
print(m1.url)
#> http://xn--punycode-eja.com/
m2 = MyModel(url='https://www.аррӏе.com/')
print(m2.url)
#> https://www.xn--80ak6aa92e.com/
m3 = MyModel(url='https://www.example.珠宝/')
print(m3.url)
#> https://www.example.xn--pbt977c/

Default: Annotated[Url, UrlConstraints(max_length=2083, allowed_schemes=['http', 'https'])]

AnyWebsocketUrl

A type that will accept any ws or wss URL.

  • TLD not required
  • Host required

Default: Annotated[Url, UrlConstraints(allowed_schemes=['ws', 'wss'])]

WebsocketUrl

A type that will accept any ws or wss URL.

  • TLD not required
  • Host required
  • Max length 2083

Default: Annotated[Url, UrlConstraints(max_length=2083, allowed_schemes=['ws', 'wss'])]

FileUrl

A type that will accept any file URL.

  • Host not required

Default: Annotated[Url, UrlConstraints(allowed_schemes=['file'])]

FtpUrl

A type that will accept ftp URL.

  • TLD not required
  • Host required

Default: Annotated[Url, UrlConstraints(allowed_schemes=['ftp'])]

PostgresDsn

A type that will accept any Postgres DSN.

  • User info required
  • TLD not required
  • Host required
  • Supports multiple hosts

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

from pydantic import (
    BaseModel,
    HttpUrl,
    PostgresDsn,
    ValidationError,
    field_validator,
)

class MyModel(BaseModel):
    url: HttpUrl

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

# the repr() method for a url will display all properties of the url
print(repr(m.url))
#> Url('http://www.example.com/')
print(m.url.scheme)
#> http
print(m.url.host)
#> www.example.com
print(m.url.port)
#> 80

class MyDatabaseModel(BaseModel):
    db: PostgresDsn

    @field_validator('db')
    def check_db_name(cls, v):
        assert v.path and len(v.path) > 1, 'database must be provided'
        return v

m = MyDatabaseModel(db='postgres://user:pass@localhost:5432/foobar')
print(m.db)
#> postgres://user:pass@localhost:5432/foobar

try:
    MyDatabaseModel(db='postgres://user:pass@localhost:5432')
except ValidationError as e:
    print(e)
    '''
    1 validation error for MyDatabaseModel
    db
      Assertion failed, database must be provided
    assert (None)
     +  where None = MultiHostUrl('postgres://user:pass@localhost:5432').path [type=assertion_error, input_value='postgres://user:pass@localhost:5432', input_type=str]
    '''

Default: Annotated[MultiHostUrl, UrlConstraints(host_required=True, allowed_schemes=['postgres', 'postgresql', 'postgresql+asyncpg', 'postgresql+pg8000', 'postgresql+psycopg', 'postgresql+psycopg2', 'postgresql+psycopg2cffi', 'postgresql+py-postgresql', 'postgresql+pygresql'])]

CockroachDsn

A type that will accept any Cockroach DSN.

  • User info required
  • TLD not required
  • Host required

Default: Annotated[Url, UrlConstraints(host_required=True, allowed_schemes=['cockroachdb', 'cockroachdb+psycopg2', 'cockroachdb+asyncpg'])]

AmqpDsn

A type that will accept any AMQP DSN.

  • User info required
  • TLD not required
  • Host required

Default: Annotated[Url, UrlConstraints(allowed_schemes=['amqp', 'amqps'])]

RedisDsn

A type that will accept any Redis DSN.

  • User info required
  • TLD not required
  • Host required (e.g., rediss://:pass@localhost)

Default: Annotated[Url, UrlConstraints(allowed_schemes=['redis', 'rediss'], default_host='localhost', default_port=6379, default_path='/0')]

MongoDsn

A type that will accept any MongoDB DSN.

  • User info not required
  • Database name not required
  • Port not required
  • User info may be passed without user part (e.g., mongodb://mongodb0.example.com:27017).

Default: Annotated[MultiHostUrl, UrlConstraints(allowed_schemes=['mongodb', 'mongodb+srv'], default_port=27017)]

KafkaDsn

A type that will accept any Kafka DSN.

  • User info required
  • TLD not required
  • Host required

Default: Annotated[Url, UrlConstraints(allowed_schemes=['kafka'], default_host='localhost', default_port=9092)]

NatsDsn

A type that will accept any NATS DSN.

NATS is a connective technology built for the ever increasingly hyper-connected world. It is a single technology that enables applications to securely communicate across any combination of cloud vendors, on-premise, edge, web and mobile, and devices. More: https://nats.io

Default: Annotated[MultiHostUrl, UrlConstraints(allowed_schemes=['nats', 'tls', 'ws'], default_host='localhost', default_port=4222)]

MySQLDsn

A type that will accept any MySQL DSN.

  • User info required
  • TLD not required
  • Host required

Default: Annotated[Url, UrlConstraints(allowed_schemes=['mysql', 'mysql+mysqlconnector', 'mysql+aiomysql', 'mysql+asyncmy', 'mysql+mysqldb', 'mysql+pymysql', 'mysql+cymysql', 'mysql+pyodbc'], default_port=3306)]

MariaDBDsn

A type that will accept any MariaDB DSN.

  • User info required
  • TLD not required
  • Host required

Default: Annotated[Url, UrlConstraints(allowed_schemes=['mariadb', 'mariadb+mariadbconnector', 'mariadb+pymysql'], default_port=3306)]

ClickHouseDsn

A type that will accept any ClickHouse DSN.

  • User info required
  • TLD not required
  • Host required

Default: Annotated[Url, UrlConstraints(allowed_schemes=['clickhouse+native', 'clickhouse+asynch'], default_host='localhost', default_port=9000)]

IPvAnyNetworkType

Type: TypeAlias Default: 'IPv4Network | IPv6Network'

pretty_email_regex

Default: _build_pretty_email_regex()

MAX_EMAIL_LENGTH

Maximum length for an email. A somewhat arbitrary but very generous number compared to what is allowed by most implementations.

Default: 2048