Python Data Structures for Humans - a library for data validation and transformation using structured models
—
Specialized field types for network-related data validation in Schematics. These types handle URLs, email addresses, IP addresses, and MAC addresses with protocol-specific validation and format normalization.
Handle web addresses with validation and optional existence checking.
class URLType(BaseType):
"""
URL field with validation and optional existence checking.
Validates URL format according to RFC standards and optionally
verifies that the URL is accessible via HTTP requests.
"""
def __init__(self, verify_exists=False, **kwargs):
"""
Initialize URL field.
Args:
verify_exists (bool): Whether to verify URL accessibility
**kwargs: Base field options
"""Handle email addresses with comprehensive format validation.
class EmailType(BaseType):
"""
Email address field with regex validation.
Validates email format according to RFC standards including
local and domain parts with comprehensive pattern matching.
"""
def __init__(self, **kwargs):
"""
Initialize email field.
Args:
**kwargs: Base field options
"""Handle various IP address formats with version-specific validation.
class IPAddressType(BaseType):
"""
IPv4 or IPv6 address field with automatic version detection.
Accepts both IPv4 and IPv6 addresses and validates format
according to the appropriate IP version standards.
"""
def __init__(self, **kwargs):
"""
Initialize IP address field.
Args:
**kwargs: Base field options
"""
class IPv4Type(BaseType):
"""
IPv4 address field with dot notation validation.
Validates IPv4 addresses in dotted decimal notation (e.g., 192.168.1.1)
with range checking for each octet.
"""
def __init__(self, **kwargs):
"""
Initialize IPv4 field.
Args:
**kwargs: Base field options
"""
class IPv6Type(BaseType):
"""
IPv6 address field with colon notation validation.
Validates IPv6 addresses in colon notation with support for
compressed notation and embedded IPv4 addresses.
"""
def __init__(self, **kwargs):
"""
Initialize IPv6 field.
Args:
**kwargs: Base field options
"""Handle network hardware addresses with flexible separator support.
class MACAddressType(BaseType):
"""
MAC address field with colon/dash separator support.
Validates MAC addresses in various formats including colon-separated
(00:11:22:33:44:55) and dash-separated (00-11-22-33-44-55) notation.
"""
def __init__(self, **kwargs):
"""
Initialize MAC address field.
Args:
**kwargs: Base field options
"""from schematics.models import Model
from schematics.types import URLType, StringType
class Website(Model):
name = StringType(required=True)
url = URLType(required=True)
verified_url = URLType(verify_exists=True) # Checks if URL is accessible
# Valid URLs
site = Website({
'name': 'Example Site',
'url': 'https://www.example.com/path?param=value',
'verified_url': 'https://httpbin.org/get' # Will be checked for accessibility
})
site.validate() # Success (assuming verified_url is accessible)
# Invalid URL format
invalid_site = Website({
'name': 'Bad Site',
'url': 'not-a-url', # Invalid URL format
})
# invalid_site.validate() would raise ValidationErrorfrom schematics.types import EmailType
class UserProfile(Model):
username = StringType(required=True)
email = EmailType(required=True)
backup_email = EmailType()
# Valid email formats
user = UserProfile({
'username': 'john_doe',
'email': 'john.doe@example.com',
'backup_email': 'john+backup@gmail.com'
})
user.validate() # Success
# Invalid email formats
invalid_user = UserProfile({
'username': 'jane',
'email': 'invalid-email', # Missing @ and domain
})
# invalid_user.validate() would raise ValidationErrorfrom schematics.types import IPAddressType, IPv4Type, IPv6Type
class NetworkConfig(Model):
any_ip = IPAddressType(required=True) # IPv4 or IPv6
server_ipv4 = IPv4Type(required=True) # IPv4 only
server_ipv6 = IPv6Type() # IPv6 only
# Mixed IP versions
config = NetworkConfig({
'any_ip': '192.168.1.1', # IPv4
'server_ipv4': '10.0.0.1', # IPv4
'server_ipv6': '2001:db8::1' # IPv6
})
config.validate() # Success
# Another valid configuration
config2 = NetworkConfig({
'any_ip': '::1', # IPv6 (localhost)
'server_ipv4': '127.0.0.1', # IPv4 localhost
})
config2.validate() # Successfrom schematics.types import MACAddressType
class NetworkInterface(Model):
name = StringType(required=True)
mac_address = MACAddressType(required=True)
# Various MAC address formats
interface1 = NetworkInterface({
'name': 'eth0',
'mac_address': '00:11:22:33:44:55' # Colon-separated
})
interface2 = NetworkInterface({
'name': 'wlan0',
'mac_address': '00-11-22-33-44-55' # Dash-separated
})
interface1.validate() # Success
interface2.validate() # Successfrom schematics.types import URLType, EmailType, IPv4Type, IntType
class ServiceConfig(Model):
service_name = StringType(required=True)
api_endpoint = URLType(required=True, verify_exists=True)
admin_email = EmailType(required=True)
server_ip = IPv4Type(required=True)
port = IntType(min_value=1, max_value=65535, required=True)
health_check_url = URLType()
# Complete service configuration
service = ServiceConfig({
'service_name': 'User Authentication API',
'api_endpoint': 'https://api.example.com/v1/auth',
'admin_email': 'admin@example.com',
'server_ip': '10.0.1.50',
'port': 8443,
'health_check_url': 'https://api.example.com/health'
})
service.validate() # Validates all network-related fields
# Export for configuration file
config_dict = service.to_primitive()class EnvironmentConfig(Model):
env_name = StringType(required=True, choices=['dev', 'staging', 'prod'])
database_urls = ListType(URLType(), min_size=1)
api_servers = ListType(IPv4Type())
notification_emails = ListType(EmailType())
load_balancer_ip = IPAddressType() # Can be IPv4 or IPv6
# Development environment
dev_config = EnvironmentConfig({
'env_name': 'dev',
'database_urls': [
'postgresql://user:pass@localhost:5432/myapp_dev'
],
'api_servers': ['127.0.0.1', '192.168.1.100'],
'notification_emails': ['dev-team@example.com'],
'load_balancer_ip': '192.168.1.10'
})
# Production environment
prod_config = EnvironmentConfig({
'env_name': 'prod',
'database_urls': [
'postgresql://user:pass@db1.example.com:5432/myapp',
'postgresql://user:pass@db2.example.com:5432/myapp'
],
'api_servers': ['10.0.1.10', '10.0.1.11', '10.0.1.12'],
'notification_emails': ['alerts@example.com', 'ops@example.com'],
'load_balancer_ip': '2001:db8::load-balancer' # IPv6
})
dev_config.validate() # Success
prod_config.validate() # SuccessInstall with Tessl CLI
npx tessl i tessl/pypi-schematics