### Depth-First Matching and Fail-Fast Error Reporting in Voluptuous Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Illustrates voluptuous's depth-first, fail-fast matching strategy with an example of a nested list schema. It shows how errors are reported immediately at the point of failure without backtracking. ```python from voluptuous import Schema, MultipleInvalid schema = Schema([[2, 3], 6]) try: schema([[6]]) raise AssertionError('MultipleInvalid not raised') except MultipleInvalid as e: exc = e print(str(exc) == "not a valid value @ data[0][0]") schema([6]) ``` -------------------------------- ### Python Range and Length Validation with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Illustrates using Voluptuous's Range and Length validators for numeric ranges and sequence/string lengths. Includes examples for inclusive/exclusive bounds, string length, list length, and combined constraints. ```python from voluptuous import Schema, Range, Length, All percentage_schema = Schema(Range(min=0, max=100)) percentage_schema(50) rating_schema = Schema(Range(min=0, max=5, min_included=False)) rating_schema(1) password_schema = Schema(All(str, Length(min=8, max=128))) password_schema('secure_password_123') tags_schema = Schema(All([str], Length(min=1, max=10))) tags_schema(['python', 'validation']) schema = Schema({ 'title': All(str, Length(min=1, max=100)), 'rating': All(int, Range(min=1, max=5)), 'tags': All([str], Length(max=5)) }) result = schema({ 'title': 'Great Product', 'rating': 4, 'tags': ['quality', 'recommended'] }) ``` -------------------------------- ### Define Custom Validation Functions Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Explains how to create custom validators using callables. It includes an example of a date string validator and a generic Coerce function for type conversion. ```python from datetime import datetime from voluptuous import Schema, Invalid def Date(fmt='%Y-%m-%d'): return lambda v: datetime.strptime(v, fmt) def Coerce(type, msg=None): def f(v): try: return type(v) except ValueError: raise Invalid(msg or ('expected %s' % type.__name__)) return f ``` -------------------------------- ### Python Element Presence Validation with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Explains how to use Voluptuous's Contains validator to ensure a specific element is present within a list or other sequence. Shows examples for required roles and permissions. ```python from voluptuous import Schema, Contains, All required_role = Schema(All(list, Contains('admin'))) required_role(['user', 'admin', 'viewer']) permissions_schema = Schema({ 'roles': All([str], Contains('authenticated')), 'scopes': All([str], Contains('read')) }) result = permissions_schema({ 'roles': ['authenticated', 'premium'], 'scopes': ['read', 'write'] }) ``` -------------------------------- ### Python Collection Membership Validation with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates the use of Voluptuous's In and NotIn validators to check for the presence or absence of a value within a collection. Includes examples with lists, enums, and combined with other validators. ```python from voluptuous import Schema, In, NotIn, All from enum import Enum status_schema = Schema(In(['draft', 'published', 'archived'])) status_schema('published') username_schema = Schema(NotIn(['admin', 'root', 'system'])) username_schema('john_doe') class Color(Enum): RED = 'red' GREEN = 'green' BLUE = 'blue' color_schema = Schema(In([c.value for c in Color])) color_schema('red') role_schema = Schema({ 'name': str, 'role': All(str, In(['user', 'moderator', 'admin'])), 'restricted_name': All(str, NotIn(['anonymous', 'guest'])) }) result = role_schema({ 'name': 'John', 'role': 'moderator', 'restricted_name': 'john_doe' }) ``` -------------------------------- ### Handling Defaults and Fallbacks with DefaultTo and SetTo Source: https://context7.com/alecthomas/voluptuous/llms.txt Shows how to provide default values for None inputs using DefaultTo and how to force specific values using SetTo. This is useful for configuration objects where missing keys or null values need sensible defaults. ```python from voluptuous import Schema, DefaultTo, SetTo, Any schema = Schema(DefaultTo(42)) schema(None) fallback_schema = Schema(Any(int, SetTo(0))) fallback_schema('invalid') config_schema = Schema({ 'timeout': DefaultTo(30), 'retries': DefaultTo(3), 'debug': DefaultTo(False) }) ``` -------------------------------- ### Defining and Using Validation Schemas Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates how to create a Schema object with type constraints, required fields, and range validators. It also shows how to handle extra keys using ALLOW_EXTRA and REMOVE_EXTRA configurations. ```python from voluptuous import Schema, Required, Optional, All, Length, Range, ALLOW_EXTRA, REMOVE_EXTRA schema = Schema({ 'name': str, 'age': int, 'email': str }) result = schema({'name': 'John', 'age': 30, 'email': 'john@example.com'}) user_schema = Schema({ Required('username'): All(str, Length(min=3, max=20)), Required('password'): All(str, Length(min=8)), Required('age'): All(int, Range(min=18, max=120)), Optional('bio', default=''): str, Optional('tags', default=list): [str] }) flexible_schema = Schema({'required_field': str}, extra=ALLOW_EXTRA) strict_schema = Schema({'keep': str}, extra=REMOVE_EXTRA) ``` -------------------------------- ### Define Schema with Defaults and Custom Errors Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates how to set default values for required or optional keys using static values or callables, and how to provide custom error messages for validation failures. ```python from voluptuous import Schema, Required, Optional schema_with_defaults = Schema({ Required('status', default='pending'): str, Required('priority', default=lambda: 5): int, Optional('notes', default=''): str }) result = schema_with_defaults({}) schema = Schema({ Required('api_key', msg='API key is required for authentication'): str }) try: schema({}) except Exception as e: print(e) ``` -------------------------------- ### Using Collection Utilities Set and Literal Source: https://context7.com/alecthomas/voluptuous/llms.txt Explains how to convert lists to sets for uniqueness and how to enforce exact value matching using the Literal validator. ```python from voluptuous import Schema from voluptuous.util import Set, Literal set_schema = Schema(Set()) set_schema([1, 2, 3, 2, 1]) literal_schema = Schema(Literal('expected_value')) literal_schema('expected_value') ``` -------------------------------- ### Implement Exclusive and Inclusive Key Constraints Source: https://context7.com/alecthomas/voluptuous/llms.txt Shows how to enforce that only one key from a group exists (Exclusive) or that all keys in a group must exist together (Inclusive). ```python from voluptuous import Schema, Exclusive, Inclusive auth_schema = Schema({ Exclusive('api_key', 'auth'): str, Exclusive('oauth_token', 'auth'): str, Exclusive('basic_auth', 'auth'): dict }) dimensions_schema = Schema({ Inclusive('width', 'size'): int, Inclusive('height', 'size'): int, 'name': str }) ``` -------------------------------- ### Transforming Data with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates how to use built-in transformers like Capitalize, Title, and Strip to clean and format input data. These can be chained using All or applied within complex dictionary schemas. ```python from voluptuous import Schema, All, Capitalize, Title, Strip, Lower cap_schema = Schema(Capitalize) cap_schema('hello world') normalize_name = Schema(All(Strip, Title)) normalize_name(' john doe ') user_schema = Schema({ 'username': All(str, Strip, Lower), 'display_name': All(str, Strip, Title), 'bio': All(str, Strip) }) ``` -------------------------------- ### Extending Existing Schemas with Voluptuous Schema.extend Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Shows how to extend an existing `voluptuous.Schema` to create a new schema with additional requirements using the `Schema.extend` method. The original schema remains unmodified. ```python from voluptuous import Schema person = Schema({'name': str}) person_with_age = person.extend({'age': int}) sorted(list(person_with_age.schema.keys())) ``` -------------------------------- ### Validate Data and Handle Exceptions Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Shows how to validate input against a schema and catch MultipleInvalid exceptions when data does not conform to the defined constraints. ```python from voluptuous import MultipleInvalid try: schema({'q': ''}) except MultipleInvalid as e: print(e) ``` -------------------------------- ### Chain Validators with All and Any Source: https://context7.com/alecthomas/voluptuous/llms.txt Explains how to use 'All' to chain multiple validation steps sequentially and 'Any' to accept values that satisfy at least one of several provided validators. ```python from voluptuous import Schema, All, Any, Length, Range, Coerce, Match username_schema = Schema(All( str, Length(min=3, max=20), Match(r'^[a-zA-Z0-9_]+$') )) flexible_id = Schema(Any(int, str)) coordinate_schema = Schema(Any( {'lat': float, 'lng': float}, [float, float], msg='Expected coordinates as dict or list' )) ``` -------------------------------- ### Validate Sets and Frozensets Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Demonstrates how to use Schema to validate sets and frozensets. It shows how specific values or types are enforced within the set structure. ```python from voluptuous import Schema, MultipleInvalid, Invalid schema = Schema({42}) assert schema({42}) == {42} schema = Schema({int, str}) assert schema({1, 2, 'abc'}) == {1, 2, 'abc'} schema = Schema(set) assert schema({1, 2}) == {1, 2} ``` -------------------------------- ### Validate Nested Schemas with All Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Demonstrates using the All validator to enforce schema rules on nested items. It shows how to capture and inspect MultipleInvalid exceptions when validation fails. ```python schema = Schema({ Required('items'): All([{ Required('foo'): str }]) }) try: schema({'items': [{}]}) except MultipleInvalid as e: exc = e ``` -------------------------------- ### Schema with Defaults and Custom Error Messages Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates how to define default values for keys and specify custom error messages for required fields. ```APIDOC ## Schema with Defaults and Custom Error Messages ### Description This section shows how to set default values for keys in a schema, including callable defaults, and how to provide custom error messages for required fields. ### Method N/A (Illustrative Python code) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from voluptuous import Schema, Required, Optional # Required key with default value schema_with_defaults = Schema({ Required('status', default='pending'): str, Required('priority', default=lambda: 5): int, # callable default Optional('notes', default=''): str }) result = schema_with_defaults({}) # Returns: {'status': 'pending', 'priority': 5, 'notes': ''} # Required with custom error message schema = Schema({ Required('api_key', msg='API key is required for authentication'): str }) try: schema({}) except Exception as e: print(e) # "API key is required for authentication @ data['api_key']" ``` ### Response N/A ``` -------------------------------- ### Exclusive and Inclusive Key Group Constraints Source: https://context7.com/alecthomas/voluptuous/llms.txt Explains and demonstrates the use of `Exclusive` and `Inclusive` constraints for defining group requirements among keys. ```APIDOC ## Exclusive and Inclusive - Key Group Constraints ### Description `Exclusive` ensures that only one key from a group can be present, while `Inclusive` ensures that all keys in a group must be present together or none at all. ### Method N/A (Illustrative Python code) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from voluptuous import Schema, Exclusive, Inclusive # Only one authentication method allowed auth_schema = Schema({ Exclusive('api_key', 'auth'): str, Exclusive('oauth_token', 'auth'): str, Exclusive('basic_auth', 'auth'): dict }) # Valid: only one auth method auth_schema({'api_key': 'abc123'}) # Invalid: multiple auth methods try: auth_schema({'api_key': 'abc123', 'oauth_token': 'xyz789'}) except Exception as e: print(e) # "two or more values in the same group of exclusion 'auth'" # Inclusive: all or nothing dimensions_schema = Schema({ Inclusive('width', 'size'): int, Inclusive('height', 'size'): int, 'name': str }) # Valid: both dimensions present dimensions_schema({'width': 100, 'height': 200, 'name': 'image'}) # Valid: neither dimension present dimensions_schema({'name': 'placeholder'}) # Invalid: only one dimension try: dimensions_schema({'width': 100, 'name': 'partial'}) except Exception as e: print(e) # "some but not all values in the same group of inclusion 'size'" ``` ### Response N/A ``` -------------------------------- ### Any - Alternative Validators Source: https://context7.com/alecthomas/voluptuous/llms.txt Explains how to use `Any` to allow a value to match one of several possible validators. ```APIDOC ## Any - Alternative Validators ### Description `Any` (alias: `Or`) accepts a value if it passes any one of the provided validators. The first successful validation result is returned. ### Method N/A (Illustrative Python code) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from voluptuous import Schema, Any, All, Coerce # Accept multiple types flexible_id = Schema(Any(int, str)) flexible_id(123) # Returns: 123 flexible_id('abc') # Returns: 'abc' # Accept specific literal values status_schema = Schema(Any('pending', 'active', 'completed', 'cancelled')) status_schema('active') # Returns: 'active' # Combine with transformations boolean_schema = Schema(Any( bool, All(str, lambda s: s.lower() in ('true', 'yes', '1')), All(int, lambda i: i != 0) )) # Accept None as valid value ullable_int = Schema(Any(None, int)) ullable_int(None) # Returns: None ullable_int(42) # Returns: 42 # Complex alternatives with custom error message coordinate_schema = Schema(Any( {'lat': float, 'lng': float}, [float, float], msg='Expected coordinates as dict or list' )) coordinate_schema({'lat': 40.7128, 'lng': -74.0060}) coordinate_schema([40.7128, -74.0060]) ``` ### Response N/A ``` -------------------------------- ### Define API Request Schema with Constraints Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Demonstrates how to create a robust schema for an API query using Voluptuous, including required fields, default values, and range constraints. ```python from voluptuous import Schema, Required, All, Length, Range schema = Schema({ Required('q'): All(str, Length(min=1)), Required('per_page', default=5): All(int, Range(min=1, max=20)), 'page': All(int, Range(min=0)), }) ``` -------------------------------- ### Extending Existing Schemas Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates the use of the extend() method to create new schemas by merging existing ones with additional fields. This allows for clean schema composition and inheritance. ```python from voluptuous import Schema, Required, Optional base_person = Schema({ Required('name'): str, Required('email'): str }) employee = base_person.extend({ Required('employee_id'): int, Required('department'): str, Optional('manager'): str }) contractor = base_person.extend({ Required('contract_end'): str, Optional('hourly_rate'): float }, required=True) ``` -------------------------------- ### Optional Dictionary Keys in Voluptuous Schema Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Demonstrates how to define schemas with optional keys using `Optional(key)` in voluptuous. It shows how required keys are enforced and how extra keys are handled when `required=True` is set for the schema. ```python from voluptuous import Optional, Schema, MultipleInvalid schema = Schema({1: 2, Optional(3): 4}, required=True) try: schema({}) raise AssertionError('MultipleInvalid not raised') except MultipleInvalid as e: exc = e print(str(exc) == "required key not provided @ data[1]") schema({1: 2}) try: schema({1: 2, 4: 5}) raise AssertionError('MultipleInvalid not raised') except MultipleInvalid as e: exc = e print(str(exc) == "extra keys not allowed @ data[4]") schema({1: 2, 3: 4}) ``` -------------------------------- ### URL and Email Validation with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates the use of FqdnUrl, Url, and Email validators for validating fully qualified domain name URLs and email addresses. These validators ensure that input strings conform to standard URL and email formats, rejecting invalid or malformed entries. ```python from voluptuous import Schema, FqdnUrl, Email, Optional, Url # Fully qualified domain name URL (no localhost) fqdn_schema = Schema(FqdnUrl()) fqdn_schema('https://www.example.com') # Valid # fqdn_schema('http://localhost') # Raises error # Email validation email_schema = Schema(Email()) email_schema('user@example.com') # Valid email_schema('user.name+tag@domain.co.uk') # Valid # Combined in a schema contact_schema = Schema({ 'email': Email(), 'website': Optional(Url()), 'company_url': Optional(FqdnUrl()) }) result = contact_schema({ 'email': 'contact@company.com', 'website': 'https://company.com', 'company_url': 'https://www.company.com' }) ``` -------------------------------- ### Value Clamping with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates the Clamp validator for constraining values within a specified minimum and maximum range. It shows how Clamp can be combined with other validators like All and Coerce for more complex validation scenarios, including one-sided clamping. ```python from voluptuous import Schema, Clamp, All, Coerce # Clamp values to range volume_schema = Schema(Clamp(min=0, max=100)) volume_schema(50) # Returns: 50 volume_schema(-10) # Returns: 0 (clamped to min) volume_schema(150) # Returns: 100 (clamped to max) # Combine with coercion percentage = Schema(All(Coerce(float), Clamp(min=0.0, max=1.0))) percentage('0.75') # Returns: 0.75 percentage('1.5') # Returns: 1.0 (clamped) percentage(-0.5) # Returns: 0.0 (clamped) # One-sided clamp non_negative = Schema(Clamp(min=0)) non_negative(-5) # Returns: 0 non_negative(100) # Returns: 100 ``` -------------------------------- ### Run Voluptuous Tests with Pytest Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Commands to execute the test suite for the Voluptuous project using pytest, including optional coverage reporting. ```bash pip install pytest pytest # With coverage report pip install pytest pytest-cov coverage>=3.0 pytest --cov=voluptuous voluptuous/tests/ ``` -------------------------------- ### Coerce - Type Conversion Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates how `Coerce` can be used to automatically convert input values to a specified type. ```APIDOC ## Coerce - Type Conversion ### Description `Coerce` attempts to convert a value to the specified type using the type's constructor. If conversion fails, validation fails with a clear error message. ### Method N/A (Illustrative Python code) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from voluptuous import Schema, Coerce, All, Range # Basic type coercion schema = Schema({ 'count': Coerce(int), 'price': Coerce(float), 'enabled': Coerce(bool) }) result = schema({ 'count': '42', # String to int 'price': '19.99', # String to float 'enabled': 1 # Int to bool }) # Returns: {'count': 42, 'price': 19.99, 'enabled': True} # Coerce with validation age_schema = Schema(All(Coerce(int), Range(min=0, max=150))) age_schema('25') # Returns: 25 ``` ### Response N/A ``` -------------------------------- ### All - Chained Validators Source: https://context7.com/alecthomas/voluptuous/llms.txt Illustrates how to use `All` to apply multiple validators sequentially to a value. ```APIDOC ## All - Chained Validators ### Description `All` (alias: `And`) applies multiple validators in sequence, where each validator's output becomes the next validator's input. Validation fails if any validator in the chain fails. ### Method N/A (Illustrative Python code) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from voluptuous import Schema, All, Length, Range, Coerce, Match # Chain multiple validators username_schema = Schema(All( str, # Must be string Length(min=3, max=20), # Length constraints Match(r'^[a-zA-Z0-9_]+$') # Alphanumeric and underscore only )) username_schema('valid_user123') # Returns: 'valid_user123' # Transform and validate price_schema = Schema(All( Coerce(float), # Convert to float Range(min=0.01, max=10000) # Must be positive and within range )) price_schema('99.99') # Returns: 99.99 (as float) price_schema(50) # Returns: 50.0 (coerced to float) # Complex nested validation order_schema = Schema({ 'items': All( list, Length(min=1, max=100), # 1-100 items [{ # List of dictionaries 'sku': All(str, Length(min=5, max=20)), 'quantity': All(int, Range(min=1)) }] ) }) ``` ### Response N/A ``` -------------------------------- ### Implement Multi-field Validation with Voluptuous Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Demonstrates how to perform cross-field validation by using a two-pass approach with the All() validator. The first pass validates data structure, while the second pass performs custom cross-field logic. ```python from voluptuous import Schema, All, Invalid def passwords_must_match(passwords): if passwords['password'] != passwords['password_again']: raise Invalid('passwords must match') return passwords schema = Schema(All( {'password': str, 'password_again': str}, passwords_must_match )) # Valid usage schema({'password': '123', 'password_again': '123'}) # Invalid usage # schema({'password': '123', 'password_again': '1337'}) ``` -------------------------------- ### Allowing None Values with Voluptuous Any Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Explains how to use `voluptuous.Any` to allow a value to be `None` or match another specified type, such as an integer. This provides flexibility in schema definitions. ```python from voluptuous import Any, Schema schema = Schema(Any(None, int)) schema(None) schema(5) ``` -------------------------------- ### Filesystem Path Validation with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Utilizes IsFile, IsDir, and PathExists validators to verify the existence and type of filesystem paths. These validators are crucial for ensuring that configuration files, data directories, or other specified paths meet the application's requirements. ```python from voluptuous import Schema, IsFile, IsDir, PathExists import os # Validate file exists config_schema = Schema({ 'config_file': IsFile(), 'data_directory': IsDir(), 'optional_path': PathExists() # File or directory }) # Example usage (paths must exist) result = config_schema({ 'config_file': '/etc/passwd', # Must be a file 'data_directory': '/tmp', # Must be a directory 'optional_path': '/usr' # Can be file or directory }) ``` -------------------------------- ### Python Regex Match and Replace with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Shows how to use Voluptuous's Match and Replace validators for regular expression validation and substitution. Covers basic matching, case-insensitive matching with compiled regex, custom error messages, and chaining replacements for string manipulation. ```python from voluptuous import Schema, Match, Replace, All import re hex_color = Schema(Match(r'^#[0-9A-Fa-f]{6}$')) hex_color('#FF5733') slug_pattern = re.compile(r'^[a-z0-9-]+$', re.IGNORECASE) slug_schema = Schema(Match(slug_pattern)) slug_schema('my-url-slug') phone_schema = Schema(Match( r'^\+?[1-9]\d{1,14}$', msg='Invalid phone number format' )) normalize_whitespace = Schema(Replace(r'\s+', ' ')) normalize_whitespace('hello world') slug_generator = Schema(All( str, Replace(r'[^a-zA-Z0-9\s-]', ''), Replace(r'\s+', '-'), lambda s: s.lower() )) slug_generator('Hello World! 123') ``` -------------------------------- ### Validate Literals and Types Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Explains how to use literals and Python types directly within a schema to enforce exact value matching or type checking. ```python from voluptuous import Schema schema_literal = Schema(1) schema_type = Schema(int) schema_literal(1) schema_type(1) ``` -------------------------------- ### Inferring Schemas from Data Source: https://context7.com/alecthomas/voluptuous/llms.txt Shows how to use Schema.infer() to automatically generate a validation schema based on an existing data sample. This is useful for rapid prototyping or validating dynamic API responses. ```python from voluptuous import Schema api_response = { 'user': {'id': 123, 'name': 'Alice', 'active': True}, 'items': ['apple', 'banana'], 'count': 2 } inferred_schema = Schema.infer(api_response) valid_data = inferred_schema({ 'user': {'id': 456, 'name': 'Bob', 'active': False}, 'items': ['orange'], 'count': 1 }) ``` -------------------------------- ### Python Format Validators (URL, Email) with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Introduces Voluptuous's built-in format validators for common string types like URLs and email addresses. Demonstrates basic usage for Url, FqdnUrl, and Email. ```python from voluptuous import Schema, Url, FqdnUrl, Email, Optional url_schema = Schema(Url()) url_schema('http://example.com') url_schema('https://example.com/path?q=1') url_schema('http://localhost:8080') ``` -------------------------------- ### Python Custom Coercion with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates how to create custom coercion functions in Voluptuous to transform input data before validation. It shows parsing dates and handling custom error messages for type coercion. ```python from datetime import datetime from voluptuous import Schema, Coerce def parse_date(value): if isinstance(value, datetime): return value return datetime.strptime(value, '%Y-%m-%d') date_schema = Schema(Coerce(parse_date)) date_schema('2024-01-15') schema = Schema(Coerce(int, msg='Please provide a valid integer')) try: schema('not a number') except Exception as e: print(e) ``` -------------------------------- ### Validate URLs Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Demonstrates the use of the Url validator to ensure input strings are valid URL formats. ```python from voluptuous import Schema, Url schema = Schema(Url()) schema('http://w3.org') ``` -------------------------------- ### Handle Objects with __slots__ and Extra Keys Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Explains how Voluptuous handles objects defined with __slots__ and how to allow extra keys using the Extra validator. ```python class SlotsStructure(Structure): __slots__ = ['q'] schema = Schema(Object({'q': 'one', Extra: object})) schema(SlotsStructure(q='one')) ``` -------------------------------- ### Remove Specific Key Patterns with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates how to remove specific key-value pairs from a dictionary based on key patterns using the `Remove` utility in Voluptuous. It also shows how to remove elements from lists based on type. ```python from voluptuous import Schema, Remove, Extra # Remove specific key patterns schema = Schema({ str: int, Remove(int): str # Remove integer keys with string values }) result = schema({ 'keep': 1, 'also_keep': 2, 123: 'remove_this' # This will be removed }) # Returns: {'keep': 1, 'also_keep': 2} # Remove from lists list_schema = Schema([int, Remove(float), Extra]) result = list_schema([1, 2, 3.5, 4, 5.5, 'extra']) # Returns: [1, 2, 4, 'extra'] (floats removed) ``` -------------------------------- ### Python: Voluptuous Basic List and Dictionary Validation Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Demonstrates basic validation of lists and dictionaries using Voluptuous. It shows how the library correctly parses simple list elements and nested dictionary structures. ```python from voluptuous import * schema = Schema(['one', {'two': 'three', 'four': ['five'], 'six': {'seven': 'eight'}}]) schema(['one']) schema([{'two': 'three'}]) ``` -------------------------------- ### Voluptuous String Transformers (Lower, Upper, Strip) Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates the use of built-in string transformation utilities in Voluptuous, such as `Lower`, `Upper`, `Capitalize`, `Title`, and `Strip`, to modify string values during the validation process. ```python from voluptuous import Schema, All, Lower, Upper, Capitalize, Title, Strip # Convert to lowercase lowercase_schema = Schema(Lower) lowercase_schema('HELLO') # Returns: 'hello' # Convert to uppercase uppercase_schema = Schema(Upper) uppercase_schema('hello') # Returns: 'HELLO' # Example using All with transformers name_schema = Schema(All(str, Capitalize, Strip)) print(name_schema(' john doe ')) # Returns: ' John doe ' (Note: Strip only removes leading/trailing whitespace, Capitalize affects first char) ``` -------------------------------- ### Perform Type Coercion Source: https://context7.com/alecthomas/voluptuous/llms.txt Demonstrates using Coerce to automatically convert input data into specific types during the validation process. ```python from voluptuous import Schema, Coerce, All, Range schema = Schema({ 'count': Coerce(int), 'price': Coerce(float), 'enabled': Coerce(bool) }) age_schema = Schema(All(Coerce(int), Range(min=0, max=150))) ``` -------------------------------- ### Implement Custom Invalid Exceptions Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Demonstrates how to raise custom subclasses of Invalid within a validator and ensure they are correctly propagated through MultipleInvalid. ```python class SpecialInvalid(Invalid): pass def custom_validator(value): raise SpecialInvalid('boom') schema = Schema({'thing': custom_validator}) ``` -------------------------------- ### Validate Objects with Class Constraints Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Shows how to use the Object validator to ensure data matches a specific class instance. It covers both strict class checking and optional class validation. ```python class Structure(object): def __init__(self, q=None): self.q = q schema = Schema(Object({'q': 'one'}, cls=Structure)) schema(Structure(q='one')) ``` -------------------------------- ### Python: Voluptuous Custom Class Validation Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Illustrates how Voluptuous can validate custom classes. If a schema is defined as a class, an instance of that class will be validated. ```python class Thing(object): pass schema = Schema(Thing) t = schema(Thing()) type(t) is Thing ``` -------------------------------- ### Python: Handle Nullable Values with Maybe Source: https://context7.com/alecthomas/voluptuous/llms.txt The Maybe validator creates an Any(None, validator) pattern, allowing values to be either None or pass a specified validator. It's useful for optional fields in schemas. ```python from voluptuous import Schema, Maybe, All, Length # Value can be None or the specified type nullable_string = Schema(Maybe(str)) nullable_string(None) # Returns: None nullable_string('hello') # Returns: 'hello' # Combined with other validators nullable_email = Schema(Maybe(All(str, Length(min=5)))) nullable_email(None) # Returns: None nullable_email('a@b.com') # Returns: 'a@b.com' # In a schema user_schema = Schema({ 'name': str, 'nickname': Maybe(str), # Optional nickname 'bio': Maybe(All(str, Length(max=500))) }) result = user_schema({ 'name': 'John', 'nickname': None, 'bio': 'Software developer' }) ``` -------------------------------- ### Validate Lists Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Shows how to define schemas for lists, where the list acts as a set of allowed values or a type constraint. ```python from voluptuous import Schema # List as set of valid values schema_set = Schema([1, 'a']) # List as type constraint schema_list = Schema(list) schema_list([1, 2]) ``` -------------------------------- ### Custom Error Messages with Voluptuous Msg Source: https://context7.com/alecthomas/voluptuous/llms.txt Shows how to wrap a Voluptuous schema with `Msg` to provide custom error messages when validation fails. This enhances user feedback by explaining validation rules more clearly. ```python from voluptuous import Schema, Msg, All, Length, Range # Custom message for validation failure age_schema = Schema(Msg( All(int, Range(min=0, max=150)), 'Age must be a number between 0 and 150' )) try: age_schema(-5) except Exception as e: print(e) # "Age must be a number between 0 and 150" # In nested schemas user_schema = Schema({ 'username': Msg( All(str, Length(min=3, max=20)), 'Username must be 3-20 characters' ), 'password': Msg( All(str, Length(min=8)), 'Password must be at least 8 characters' ) }) ``` -------------------------------- ### Optional Validator Comparison Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Illustrates the behavior of the Optional() validator when used in comparison operations. ```APIDOC ## Optional Validator Comparison ### Description This example shows that `Optional('Classification') < 'Name'` evaluates to `True`, handling potential `AttributeError` gracefully. ### Method N/A (Illustrative Example) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from voluptuous import Optional result = Optional('Classification') < 'Name' print(result) ``` ### Response #### Success Response (200) Returns `True`. #### Response Example ``` True ``` ``` -------------------------------- ### Object Validator with Custom Classes Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Demonstrates the usage of the Object() validator with custom classes, including optional class specification and type checking. ```APIDOC ## Object Validator with Custom Classes ### Description This section covers the `Object()` validator's behavior with custom classes. It shows how `cls` argument works for type checking and how it handles objects with `__slots__`. ### Method N/A (Illustrative Example) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from voluptuous import Schema, Object, MultipleInvalid class Structure(object): def __init__(self, q=None): self.q = q def __repr__(self): return '{0.__name__}(q={1.q!r})'.format(type(self), self) # Validator with optional cls argument schema_optional_cls = Schema(Object({'q': 'one'})) # Validator with cls argument for type checking schema_with_cls = Schema(Object({'q': 'one'}, cls=Structure)) # Example usage instance = Structure(q='one') print(schema_optional_cls(instance) == instance) try: schema_with_cls(Structure(q='two')) # This should pass print(schema_with_cls(Structure(q='two'))) except MultipleInvalid as e: print(e) from collections import namedtuple NamedTuple = namedtuple('NamedTuple', ('q',)) named_instance = NamedTuple(q='one') # Object validator should treat cls argument as optional print(schema_optional_cls(named_instance) == named_instance) print(schema_optional_cls(named_instance)) # If cls argument is provided, type checking occurs try: schema_with_cls(named_instance) except MultipleInvalid as e: print(e) # Example with __slots__ class SlotsStructure(Structure): __slots__ = ['q'] schema_slots = Schema(Object({'q': 'one'})) slots_instance = SlotsStructure(q='one') print(schema_slots(slots_instance)) class DictStructure(object): __slots__ = ['q', '__dict__'] def __init__(self, q=None, page=None): self.q = q self.page = page def __repr__(self): return '{0.__name__}(q={1.q!r}, page={1.page!r})'.format(type(self), self) dict_instance = DictStructure(q='one') dict_instance.page = 1 try: schema_slots(dict_instance) except MultipleInvalid as e: print(e) ``` ### Response #### Success Response (200) Returns the validated object if it matches the schema. #### Response Example ``` True Structure(q='one') NamedTuple(q='one') expected a SlotsStructure(q='one') extra keys not allowed @ data['page'] ``` ``` -------------------------------- ### All() Validator with Nested Structures Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Illustrates how the All() validator correctly propagates errors from nested structures, ensuring consistent error reporting. ```APIDOC ## All() Validator with Nested Structures ### Description This example shows that schemas built with `All()` should provide the same error messages as the original validator when dealing with nested data structures. ### Method N/A (Illustrative Example) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from voluptuous import Schema, Required, All, MultipleInvalid schema = Schema({ Required('items'): All([{ Required('foo'): str }]) }) try: schema({'items': [{}]}) raise AssertionError('MultipleInvalid not raised') except MultipleInvalid as e: exc = e print(str(exc)) ``` ### Response #### Success Response (200) N/A (This is an error-raising example) #### Response Example ``` required key not provided @ data['items'][0]['foo'] ``` ``` -------------------------------- ### Date and Datetime Validation with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Provides Date and Datetime validators for parsing and validating date and datetime strings. Supports default ISO formats as well as custom formats, enabling flexible handling of temporal data in various applications. ```python from voluptuous import Schema, Date, Datetime # Default ISO format datetime (YYYY-MM-DDTHH:MM:SS.ffffffZ) datetime_schema = Schema(Datetime()) datetime_schema('2024-01-15T10:30:00.000000Z') # Custom datetime format custom_datetime = Schema(Datetime(format='%Y-%m-%d %H:%M:%S')) custom_datetime('2024-01-15 10:30:00') # Default date format (YYYY-MM-DD) date_schema = Schema(Date()) date_schema('2024-01-15') # Custom date format us_date = Schema(Date(format='%m/%d/%Y')) us_date('01/15/2024') # In a larger schema event_schema = Schema({ 'name': str, 'date': Date(), 'start_time': Datetime(format='%Y-%m-%d %H:%M'), 'end_time': Datetime(format='%Y-%m-%d %H:%M') }) result = event_schema({ 'name': 'Conference', 'date': '2024-06-15', 'start_time': '2024-06-15 09:00', 'end_time': '2024-06-15 17:00' }) ``` -------------------------------- ### Python: Voluptuous Depth-First Error Reporting Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Demonstrates Voluptuous's depth-first error reporting mechanism. When an error occurs in a nested structure, the error message and path reflect the deepest point of failure. ```python from voluptuous import * validate = Schema({'one': {'two': 'three', 'four': 'five'}}) try: validate({'one': {'four': 'six'}}) except Invalid as e: print(e) print(e.path) ``` -------------------------------- ### Python: Voluptuous Type Validation with Built-in Types Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Shows how Voluptuous can use built-in Python types like dict, list, and tuple as validators. This allows for straightforward validation of common data structures. ```python Schema(dict)({'a': 1, 'b': 2}) Schema(list)([1,2,3]) Schema(tuple)((1,2,3)) ``` -------------------------------- ### Configure Dictionary Validation Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Covers dictionary schema validation, including handling extra keys using ALLOW_EXTRA or REMOVE_EXTRA, and enforcing required keys with the Required marker. ```python from voluptuous import Schema, ALLOW_EXTRA, REMOVE_EXTRA, Required, Extra # Handling extra keys schema = Schema({2: 3}, extra=ALLOW_EXTRA) assert schema({1: 2, 2: 3}) == {1: 2, 2: 3} # Required keys schema = Schema({Required(1): 2, 3: 4}) assert schema({1: 2}) == {1: 2} ``` -------------------------------- ### Validating Objects with Voluptuous Object Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Demonstrates how to use `voluptuous.Object` to validate object attributes against a schema. This is useful for validating instances of custom classes based on their attributes. ```python from voluptuous import Schema, Object class Structure(object): def __init__(self, q=None): self.q = q def __repr__(self): return ''.format(self) schema = Schema(Object({'q': 'one'}, cls=Structure)) schema(Structure(q='one')) ``` -------------------------------- ### Python: Voluptuous Validation with Extra Fields Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Illustrates how Voluptuous handles validation when extra fields are present in the data. It shows that by default, extra fields are allowed if 'Extra' is specified in the schema. ```python from voluptuous import * schema = Schema({'one': 1, Extra: object}) schema({'two': 'two', 'one': 1}) schema = Schema({'one': 1}) try: schema({'two': 2}) raise AssertionError('MultipleInvalid not raised') except MultipleInvalid as e: exc = e str(exc) ``` -------------------------------- ### Custom Validation and Error Reporting in Voluptuous Source: https://github.com/alecthomas/voluptuous/blob/master/README.md Details how custom validators in voluptuous should raise `Invalid` exceptions for validation failures. It explains the `path`, `msg`, and `error_message` attributes of `Invalid` exceptions for detailed error reporting. ```python from voluptuous import Schema, Invalid, MultipleInvalid def validate_email(email): if "@" not in email: raise Invalid("This email is invalid.") return email schema = Schema({"email": validate_email}) try: schema({"email": "whatever"}) except MultipleInvalid as e: exc = e print(str(exc)) print(exc.path) print(exc.msg) print(exc.error_message) ``` -------------------------------- ### Python: Voluptuous Subclass Validation for Dict and List Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Demonstrates that Voluptuous correctly validates instances of subclasses of dict or list, returning instances of the original subclass. ```python class Dict(dict): pass d = Schema(dict)(Dict(a=1, b=2)) type(d) is Dict class List(list): pass l = Schema(list)(List([1,2,3])) type(l) is List ``` -------------------------------- ### Python: Voluptuous Nested Index and Container Error Reporting Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Illustrates Voluptuous's error reporting for invalid values within nested list structures. It highlights how errors specify the exact index and container type. ```python from voluptuous import * try: schema(['one', 'two']) raise AssertionError('MultipleInvalid not raised') except MultipleInvalid as e: exc = e str(exc) == 'expected a dictionary @ data[1]' ``` -------------------------------- ### Python: Voluptuous Multiple Error Reporting Source: https://github.com/alecthomas/voluptuous/blob/master/voluptuous/tests/tests.md Illustrates Voluptuous's ability to report multiple validation errors simultaneously. This is useful for providing comprehensive feedback to the user. ```python from voluptuous import * schema = Schema({'one': 1, 'two': 2}) try: schema({'one': 2, 'two': 3, 'three': 4}) except MultipleInvalid as e: errors = sorted(e.errors, key=lambda k: str(k)) print([str(i) for i in errors]) schema = Schema([[1], [2], [3]]) try: schema([1, 2, 3]) except MultipleInvalid as e: print([str(i) for i in e.errors]) ``` -------------------------------- ### Boolean Value Validation with Voluptuous Source: https://context7.com/alecthomas/voluptuous/llms.txt Covers Boolean, IsTrue, and IsFalse validators for handling boolean values, including string representations. These validators simplify the process of converting various truthy and falsy inputs into their corresponding boolean equivalents. ```python from voluptuous import Schema, Boolean, IsTrue, IsFalse # Convert various truthy/falsy values to boolean bool_schema = Schema(Boolean()) bool_schema(True) # Returns: True bool_schema('true') # Returns: True bool_schema('yes') # Returns: True bool_schema('1') # Returns: True bool_schema('on') # Returns: True bool_schema(False) # Returns: False bool_schema('false') # Returns: False bool_schema('no') # Returns: False bool_schema('0') # Returns: False bool_schema('off') # Returns: False # Must be truthy truthy_schema = Schema(IsTrue()) truthy_schema([1, 2, 3]) # Returns: [1, 2, 3] truthy_schema(1) # Returns: 1 # truthy_schema([]) # Raises: "value was not true" # Must be falsy falsy_schema = Schema(IsFalse()) falsy_schema([]) # Returns: [] falsy_schema(0) # Returns: 0 falsy_schema(False) # Returns: False # falsy_schema(True) # Raises: "value was not false" ```