### Install Trafaret from Source Source: https://github.com/deepwalker/trafaret/blob/master/docs/installation.rst Installs the trafaret library after obtaining the source code (either via cloning or downloading a tarball). This command is run from the root directory of the cloned repository. ```shell python setup.py install ``` -------------------------------- ### Install Trafaret using Pip Source: https://github.com/deepwalker/trafaret/blob/master/docs/installation.rst Installs the latest stable release of the trafaret library using pip. This is the recommended installation method. Ensure pip is installed. ```shell pip install trafaret ``` -------------------------------- ### Clone Trafaret Repository Source: https://github.com/deepwalker/trafaret/blob/master/docs/installation.rst Clones the trafaret project repository from GitHub using git. This allows for installation from source. ```shell git clone git://github.com/Deepwalker/trafaret ``` -------------------------------- ### Download Trafaret Tarball Source: https://github.com/deepwalker/trafaret/blob/master/docs/installation.rst Downloads the trafaret project source code as a tarball from GitHub. This is an alternative method for installation from source. ```shell curl -OL https://github.com/Deepwalker/trafaret/tarball/master ``` -------------------------------- ### Constructing Trafaret Validators with Python Source: https://github.com/deepwalker/trafaret/blob/master/README.rst Demonstrates how to use the `construct` function from `trafaret.constructor` to create a validator from a dictionary definition. This validator can then be used to check and transform input data. It shows a successful validation and an example of a `DataError` when the input does not conform to the schema. ```python from trafaret.constructor import construct validator = construct({'a': int, 'b': [str]}) print(validator({'a': 5, 'b': ['lorem', 'ipsum']})) try: validator({'a': 5, 'b': ['gorky', 9]}) except Exception as e: print(e) ``` -------------------------------- ### Python Example: Sending Book Data via Requests POST Source: https://github.com/deepwalker/trafaret/blob/master/docs/web_use.rst Demonstrates how to send book creation data to a local aiohttp server using the `requests` library. The data is structured according to the expected schema, including camelCase keys. ```python import requests as r data = { "bookTitle": "Glue", "bookPageCount": 436, "bookDescription": "Glue tells the stories of four Scottish boys over four decades...", "bookPrice": 423, "bookFirstAuthor": "Welsh", "bookAuthors": ["Welsh"] } r.post("http://0.0.0.0:8000/", json=data).text ``` -------------------------------- ### Python: Advanced trafaret Key usage for data conversion Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Provides an example of advanced `trafaret.Key` usage, demonstrating how to rename keys, set defaults, mark keys as optional, and apply custom conversion functions (like hashing or string splitting) during dictionary validation. ```python import trafaret as t import hashlib hash_md5 = lambda d: hashlib.md5(d.encode()).hexdigest() comma_to_list = lambda d: [s.strip() for s in d.split(',')] converter = t.Dict({ t.Key('userNameFirst') >> 'name': t.String, t.Key('userNameSecond') >> 'second_name': t.String, t.Key('userPassword') >> 'password': hash_md5, t.Key('userEmail', optional=True, to_name='email'): t.String, t.Key('userTitle', default='Bachelor', to_name='title'): t.String, t.Key('userRoles', to_name='roles'): comma_to_list, }) ``` ```python import trafaret as t converter = t.Dict( t.Key('userNameFirst', to_name='name', trafaret=t.String), t.Key('userNameSecond', to_name='second_name', trafaret=t.String), ) ``` -------------------------------- ### Python: Basic String Validation with Trafaret Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Illustrates the basic usage of Trafaret's `String` checker to validate if a value is a string. It shows a simple check and examples of using `allow_blank`, `min_length`, and `max_length` options. ```python t.String().check('this is my string') # 'this is my string' ``` ```python t.String(allow_blank=True).check('') # '' ``` ```python t.String(min_length=1, max_length=10).check('no so long') # 'no so long' ``` -------------------------------- ### aiohttp Handlers for Creating and Updating Books Source: https://github.com/deepwalker/trafaret/blob/master/docs/web_use.rst Provides example aiohttp web handlers for creating and updating books. These handlers use the previously defined trafaret schemas (`prepare_data_for_create_book`, `prepare_data_for_update_book`) to validate incoming JSON data. ```python from aiohttp import web # Assume prepare_data_for_create_book and prepare_data_for_update_book are defined elsewhere async def create_book(req): """Hadler for create book""" raw_data = await req.json() data = prepare_data_for_create_book(raw_data) # do something ... return web.json_response({"created": True}) async def update_book(req): """Handler for update book by id""" raw_data = await req.json() data = prepare_data_for_update_book(raw_data) # do something ... return web.json_response({"updated": True}) # setup an application app = web.Application() app.add_routes([ web.post('/', create_book), web.put('/', update_book) ]) web.run_app(app, port=8000) ``` -------------------------------- ### Python: Convert values to integer with ToInt and URL query parameters Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Demonstrates Trafaret's ToInt validator for converting values to integers, including handling range constraints. The example shows its practical application in validating URL query parameters, converting a 'node' parameter to an integer and providing a default value if the parameter is missing. ```python import trafaret as t from yarl import URL query_validator = t.Dict({ t.Key('node', default=0): t.ToInt(gte=0), }) url = URL('https://www.amazon.com/b?node=18637575011') query_validator.check(url.query) url = URL('https://www.amazon.com/b') query_validator.check(url.query) ``` -------------------------------- ### Example Handlers with Error Decorator (Python) Source: https://github.com/deepwalker/trafaret/blob/master/docs/web_use.rst Illustrates how to apply the `with_error` decorator to asynchronous handler functions like `create_book` and `update_book`. This ensures that any validation errors caught by Trafaret within these handlers are returned as JSON error messages. ```python @with_error async def create_book(req): """Hadler for create book""" ... @with_error async def update_book(req): """Handler for update book by id""" ... ``` -------------------------------- ### Python: Restructure dictionary with trafaret Key and fold Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Illustrates how to use `trafaret.Key` with the `>>` operator for renaming and `trafaret.utils.fold` to restructure a dictionary. This example shows how to group related fields (like author's first and last name) into nested dictionaries. ```python import trafaret as t from trafaret.utils import fold data = {"title": "Glue", "authorFirstName": "Irvine", "authorLastName": "Welsh"} book_validator = t.Dict({ "title": t.String, t.Key('authorFirstName') >> 'author__first_name': t.String, t.Key('authorLastName') >> 'author__last_name': t.String, }) >> fold book_validator.check(data) ``` -------------------------------- ### Python: Error Handling and Extraction with Trafaret Source: https://context7.com/deepwalker/trafaret/llms.txt Gracefully handle validation errors using Trafaret's `t.extract_error` to get a dictionary of validation failures and `t.catch_error` to programmatically capture `DataError` exceptions during validation. ```python import trafaret as t # Extract error messages validator = t.Dict({ 'name': t.String(), 'age': t.Int(), 'email': t.Email, }) error = t.extract_error(validator, { 'name': 'John', 'age': 'invalid', 'email': 'not-an-email' }) print(error) # {'age': 'value is not int', 'email': 'value is not a valid email address'} # Catch errors programmatically result = t.catch_error(t.Int(), 'not a number') if isinstance(result, t.DataError): print(f"Validation failed: {result}") ``` -------------------------------- ### Python Example: Custom Decorator for Trafaret Error Handling Source: https://github.com/deepwalker/trafaret/blob/master/docs/web_use.rst Shows a Python decorator named `with_error` intended to wrap web handlers. Its purpose is to catch `t.DataError` exceptions raised by trafaret during data validation and provide a structured error response. ```python from functools import wraps import trafaret as t def with_error(fn): """ This is decorator for wrapping web handlers which need to represent """ @wraps(fn) async def wrapper(req): try: return await fn(req) except t.DataError as e: # Handle the error, e.g., return a JSON response with error details return web.json_response({'error': str(e)}, status=400) return wrapper ``` -------------------------------- ### Python: Regular Expression String Matching with Trafaret Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Illustrates using Trafaret's `Regexp` checker to validate strings against a provided regular expression. It highlights the use of `$` for full string matching. ```python t.Regexp(regexp=r"\w{3}-\w{3}-\w{4}").check('544-343-7564') # '544-343-7564' ``` -------------------------------- ### Untitled No description -------------------------------- ### Use Constructor Shortcut Syntax for Trafaret Validators Source: https://context7.com/deepwalker/trafaret/llms.txt This code demonstrates the constructor shortcut syntax in Trafaret, allowing the definition of validators using Python's native types and structures. It covers simple type mapping, optional keys, tuple validation, nested structures, and basic error handling. ```python from trafaret.constructor import construct # Simple type mapping validator = construct({'a': int, 'b': [str]}) result = validator({'a': 5, 'b': ['lorem', 'ipsum']}) # Returns: {'a': 5, 'b': ['lorem', 'ipsum']} # Optional keys with '?' suffix validator = construct({ 'name': str, 'age': int, 'email?': str # Optional key }) result = validator({'name': 'Alice', 'age': 30}) # Returns: {'name': 'Alice', 'age': 30} # Tuple validation validator = construct((int, str, float)) result = validator((1, 'hello', 3.14)) # Returns: (1, 'hello', 3.14) # Nested structures validator = construct({ 'users': [{'id': int, 'name': str}], 'metadata': {'version': int} }) result = validator({ 'users': [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}], 'metadata': {'version': 1} }) # Error handling try: construct({'a': int}).check({'a': 'not_an_int'}) except Exception as e: print(e) # DataError with conversion error ``` -------------------------------- ### Python: Bytestring to String Conversion with Trafaret's FromBytes Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Explains and demonstrates Trafaret's `FromBytes` checker for converting bytestrings to strings using specified encodings (defaults to UTF-8). It shows how it can be combined with `t.String` using the `|` operator for flexible input. ```python unicode_or_utf16 = t.String | t.FromBytes(encoding='utf-16') unicode_or_utf16.check(b'\xff\xfet\x00r\x00a\x00f\x00a\x00r\x00e\x00t\x00') # 'trafaret' unicode_or_utf16.check('trafaret') # 'trafaret' ``` ```python t.FromBytes().check(b'trafaret') # 'trafaret' ``` -------------------------------- ### Untitled No description -------------------------------- ### Creating Datetime Trafarets with Python Source: https://github.com/deepwalker/trafaret/blob/master/README.rst Shows how to define a Trafaret validator for a dictionary representing date components (year, month, day) and then transform it into a `datetime.datetime` object using a lambda function. This illustrates data structure validation and subsequent transformation. ```python import datetime import trafaret as t date = t.Dict(year=t.Int, month=t.Int, day=t.Int) >> (lambda d: datetime.datetime(**d)) assert date.check({'year': 2012, 'month': 1, 'day': 12}) == datetime.datetime(2012, 1, 12) ``` -------------------------------- ### Trafaret Schema for Book Creation and Update with Camel/Snake Case Handling Source: https://github.com/deepwalker/trafaret/blob/master/docs/web_use.rst Illustrates defining trafaret schemas for book creation and updates, including renaming keys from camelCase to snake_case (e.g., 'bookTitle' to 'title'). It also shows how to set default values, optional fields, and combine schemas. ```python import trafaret as t create_book_chacker = t.Dict({ t.Key('bookTitle', to_name='title'): t.String, t.Key('bookPageCount', to_name='pages'): t.Int, t.Key('bookDescription', to_name='description'): t.String(min_length=20), t.Key('bookPrice', to_name='price', default=100): t.Int >= 100, t.Key('bookIsFree', optional=True, to_name='is_free'): t.Bool, t.Key('bookFirstAuthor', to_name='first_author'): t.String(max_length=10), t.Key('bookAuthors', to_name='authors'): t.List(t.String(max_length=10)), }) update_user_chacker = create_book_chacker + {"id": t.Int} ``` -------------------------------- ### Python: URL Validation with Trafaret Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Shows how to use Trafaret's `URL` checker to validate if a string represents a valid URL, including those with query parameters and anchors. ```python t.URL.check('http://example.net/resource/?param=value#anchor') # 'http://example.net/resource/?param=value#anchor' ``` -------------------------------- ### Python: Alternate Or Syntax with Pipe Operator Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Demonstrates the use of the pipe operator '|' as an alternative to the Or constructor for defining validation rules that accept multiple types. This is a more concise way to express disjunctions in Trafaret. ```python (t.Int | t.String).check('five') # 'five' ``` -------------------------------- ### Regex Validation and Transformation in Python Source: https://github.com/deepwalker/trafaret/blob/master/README.rst Illustrates how to use `RegexpRaw` to validate a string against a regular expression and then extract a specific group using a lambda function. This snippet demonstrates pattern matching and data extraction. ```python import trafaret as t c = t.RegexpRaw(r'^name=(\w+)$') >> (lambda m: m.group(1)) print(c.check('name=Jeff')) ``` -------------------------------- ### Python: IPv6 Address Validation with Trafaret Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Demonstrates Trafaret's `IPv6` checker for validating IPv6 addresses. ```python t.IPv6.check('2001:0db8:0000:0042:0000:8a2e:0370:7334') # '2001:0db8:0000:0042:0000:8a2e:0370:7334' ``` -------------------------------- ### Python: Validate dictionary keys and apply custom logic with KeysSubset Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Demonstrates the use of Trafaret's KeysSubset for advanced key validation and transformation. It defines a dictionary validator that checks for 'pwd' and 'pwd1' keys and applies a custom lambda function to compare their values, ensuring they are equal. It also validates a 'key1' string. ```python from trafaret.extras import KeysSubset cmp_pwds = lambda x: { 'pwd': x['pwd'] if x.get('pwd') == x.get('pwd1') else DataError('Not equal') } d = Dict({KeysSubset('pwd', 'pwd1'): cmp_pwds, 'key1': String}) d.check({'pwd': 'a', 'pwd1': 'a', 'key1': 'b'}).keys() ``` -------------------------------- ### Python: Advanced String Parsing with RegexpRaw and Transformers Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Demonstrates `RegexpRaw` for extracting groups from strings and combining it with transformer functions (like `>>` and `&`) to create complex data extraction and conversion pipelines. ```python name_checker = t.RegexpRaw(r'^name=(\w+)$') >> (lambda m: m.groups()[0]) name_checker.check('name=Jeff') # 'Jeff' ``` ```python from datetime import datetime def to_datetime(m): return datetime(*[int(i) for i in m.groups()]) date_checker = t.RegexpRaw(regexp='^year=(\d+), month=(\d+), day=(\d+)$') & to_datetime date_checker.check('year=2019, month=07, day=23') # datetime.datetime(2019, 7, 23, 0, 0) ``` -------------------------------- ### Python: IPv4 Address Validation with Trafaret Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Illustrates the use of Trafaret's `IPv4` checker to validate if a string is a valid IPv4 address. ```python t.IPv4.check('127.0.0.1') # '127.0.0.1' ``` -------------------------------- ### Python: Email Validation with Trafaret Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Demonstrates how to use Trafaret's built-in `Email` checker to validate if a given string is a valid email address. ```python t.Email.check('someone@example.net') # 'someone@example.net' ``` -------------------------------- ### Custom Datetime Parsing with Python and Arrow Source: https://github.com/deepwalker/trafaret/blob/master/README.rst Presents a custom function `check_datetime` that uses the `arrow` library to parse date/time strings. If parsing fails, it returns a `trafaret.DataError`, showcasing how to integrate external libraries for complex validation logic within Trafaret. ```python import arrow import trafaret as t def check_datetime(str): try: return arrow.get(str).naive except arrow.parser.ParserError: return t.DataError('value is not in proper date/time format') ``` -------------------------------- ### Python: Convert to Decimal with rounding and constraints Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Illustrates Trafaret's ToDecimal validator for converting values to Decimal type with specific precision and rounding rules. It combines type conversion with custom validation logic using lambda functions and Trafaret's binary operators (&) to enforce constraints like positivity and precise decimal places. ```python from decimal import Decimal, ROUND_HALF_UP import trafaret as t validator = t.Dict({ "name": t.String, "salary": t.ToDecimal(gt=0) & ( lambda value: value.quantize( Decimal('.0000'), rounding=ROUND_HALF_UP ) ), }) validator.check({"name": "Bob", "salary": "1000.0"}) validator.check({"name": "Tom", "salary": 1000.0005}) validator.check({"name": "Jay", "salary": 1000.00049}) validator.check({"name": "Joe", "salary": -1000}) ``` -------------------------------- ### Python: Custom Key getter for aiohttp MultiDict Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Demonstrates how to subclass Trafaret's Key to handle specific data structures like aiohttp's MultiDict. The MDKey class overrides the get_data method to use MultiDict's get_all method, enabling correct retrieval of multiple values for a given key. This is useful when dealing with complex request data. ```python class MDKey(t.Key): def get_data(data, default): return data.get_all(self.name, default) t.Dict({MDKey('users'): t.List(t.String)}) ``` -------------------------------- ### Untitled No description -------------------------------- ### Python: Complex Data Transformation Pipeline with Trafaret Source: https://context7.com/deepwalker/trafaret/llms.txt Build sophisticated data transformation pipelines using Trafaret's `Dict` and key mapping (`>>`). This allows for renaming keys, applying transformation functions (like hashing or string manipulation), and handling nested structures, including using `trafaret.utils.fold`. ```python import trafaret as t import hashlib from trafaret.utils import fold # External API data format sample_data = { 'userNameFirst': 'Adam', 'userNameSecond': 'Smith', 'userPassword': 'supersecretpassword', 'userEmail': 'adam@smith.math.edu', 'userRoles': 'teacher, worker, admin', } # Transformation functions hash_md5 = lambda d: hashlib.md5(d.encode()).hexdigest() comma_to_list = lambda d: [s.strip() for s in d.split(',')] # Define comprehensive transformation pipeline converter = t.Dict({ t.Key('userNameFirst') >> 'name': t.String(), t.Key('userNameSecond') >> 'second_name': t.String(), t.Key('userPassword') >> 'password': hash_md5, t.Key('userEmail', optional=True, to_name='email'): t.Email, t.Key('userTitle', default='Bachelor', to_name='title'): t.String(), t.Key('userRoles', to_name='roles'): comma_to_list, }) result = converter.check(sample_data) # Returns: { # 'name': 'Adam', # 'second_name': 'Smith', # 'password': '4a3f285427c83c66a0b468e0d7f7c7b5', # 'email': 'adam@smith.math.edu', # 'title': 'Bachelor', # 'roles': ['teacher', 'worker', 'admin'] # } # Nested transformation with fold utility nested_converter = t.Dict({ t.Key('api__user__name') >> 'user__info__name': t.String(), t.Key('api__user__age') >> 'user__info__age': t.ToInt(), }) >> fold result = nested_converter.check({ 'api__user__name': 'Bob', 'api__user__age': '35' }) # Returns: {'user': {'info': {'name': 'Bob', 'age': 35}}} ``` -------------------------------- ### Python: IP Address Validation (IPv4/IPv6) with Trafaret Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Shows how Trafaret's `IP` checker can validate both IPv4 and IPv6 addresses. ```python t.IP.check('127.0.0.1') # '127.0.0.1' t.IP.check('2001:0db8:0000:0042:0000:8a2e:0370:7334') # '2001:0db8:0000:0042:0000:8a2e:0370:7334' ``` -------------------------------- ### Python: Convert various inputs to boolean with ToBool Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Illustrates Trafaret's ToBool validator, which converts a variety of string representations (case-insensitive), integers (1 and 0), booleans, and None to their corresponding boolean values. This validator is flexible for handling user input or data from less strict sources. ```python equivalents = ('t', 'true', 'y', 'yes', 'on', '1', '1.0', 'false', 'n', 'no', 'off', '0', '0.0', 'none') for value in equivalents: print("%s is %s" % (value, t.ToBool().check(value))) t.ToBool().check(1) t.ToBool().check(False) t.ToBool().check(None) ``` -------------------------------- ### Python: Using Fold for Data Restructuring Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Illustrates the 'fold' utility for reshaping nested dictionaries. It allows specifying a prefix and delimiter to flatten keys, making data more manageable for validation. This is useful when dealing with data from external sources that have a different structure. ```python new_fold = lambda x: fold(x, 'data', '.') book_validator = t.Dict({ "data.author.first_name": t.String, "data.author.last_name": t.String, }) >> new_fold book_validator.check({ "data.author.first_name": 'Irvine', "data.author.last_name": 'Welsh', }) # {'author': {'first_name': 'Irvine', 'last_name': 'Welsh'}} ``` -------------------------------- ### Python: Validate dictionary structure with trafaret Dict Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Demonstrates basic dictionary validation using `trafaret.Dict`. It defines a validator for a dictionary with 'username' and 'email' fields and then checks a sample dictionary against this validator. ```python import trafaret as t login_validator = t.Dict({'username': t.String(max_length=10), 'email': t.Email}) login_validator.check({'username': 'Misha', 'email': 'misha@gmail.com'}) ``` -------------------------------- ### Python: Bytes String Validation with Trafaret Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Shows how to use Trafaret's `Bytes` checker to validate if a given value is a bytes string. ```python t.Bytes().check(b'bytes string') ``` -------------------------------- ### Python: String or Bytes Validation with Trafaret's AnyString Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Demonstrates the `AnyString` checker in Trafaret, which can validate values that are either standard strings or bytes strings. ```python for item in ['string', b'bytes string']: print(t.AnyString().check(item)) ``` -------------------------------- ### Untitled No description -------------------------------- ### Renaming Dictionary Keys with Trafaret in Python Source: https://github.com/deepwalker/trafaret/blob/master/README.rst Demonstrates how to rename keys within a dictionary using Trafaret. It defines a `Dict` trafaret where a specific key ('uNJ') is mapped to a new key ('user_name'), showing how to transform dictionary structures. ```python import trafaret as t c = t.Dict({(t.Key('uNJ') >> 'user_name'): t.String}) print(c.check({'uNJ': 'Adam'})) ``` -------------------------------- ### Perform Regex Matching and Extraction with Trafaret Source: https://context7.com/deepwalker/trafaret/llms.txt This section covers using Trafaret's Regexp validators for pattern matching and data extraction. It shows basic regex validation, extracting specific groups using RegexpRaw, case-insensitive matching, and complex extraction with transformations, including error handling. ```python import trafaret as t # Basic regex matching pattern_validator = t.Regexp(r'^\w+-\w+$') result = pattern_validator.check('hello-world') # Returns: 'hello-world' # Regex with extraction using RegexpRaw extractor = t.RegexpRaw(r'^name=(\w+)$') >> (lambda m: m.group(1)) result = extractor.check('name=Jeff') # Returns: 'Jeff' # Case-insensitive matching with transformation validator = t.RegexpString(r'^[a-z]+$') result = validator.check('hello') # Returns: 'hello' # Complex extraction and transformation phone_extractor = t.RegexpRaw(r'^\+?(\d{1,3})-?(\d{3})-?(\d{4})$') >> ( lambda m: {'country': m.group(1), 'area': m.group(2), 'number': m.group(3)} ) result = phone_extractor.check('+1-555-1234') # Returns: {'country': '1', 'area': '555', 'number': '1234'} # Error handling try: t.Regexp(r'^\d+$').check('abc123') except t.DataError as e: print(t.extract_error(t.Regexp(r'^\d+$'), 'abc123')) # 'value does not match regexp' ``` -------------------------------- ### Python: Validate and Convert Date Structures with Trafaret Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Demonstrates how to use Trafaret to validate a dictionary representing a date and convert it into a datetime object. It defines a custom validator using `t.Dict` and a lambda function for conversion, handling potential `t.DataError` exceptions. ```python import datetime import trafaret as t date = t.Dict(year=t.Int, month=t.Int, day=t.Int) & (lambda d: datetime.datetime(**d)) def validate_date(data): try: return date.check(data), False except t.DataError as e: return False, e.as_dict() validate_date({'year': 2012, 'month': 1}) # (False, {'day': 'is required'}) validate_date({'year': 2012, 'month': 1, 'day': 12}) # (datetime.datetime(2012, 1, 12, 0, 0), False) ``` -------------------------------- ### Python: Use a simple function as a Trafaret validator Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Shows how to use a simple callable, like a function, as a validator within Trafaret. The 'simple_key' function acts as a trafaret, yielding data that conforms to the expected structure. This allows for flexible validation logic beyond predefined Trafaret types. ```python def simple_key(value): yield 'simple', 'simple data', [] check_args = t.Dict(simple_key) ``` -------------------------------- ### Validate Email, URL, and IP Addresses with Trafaret Source: https://context7.com/deepwalker/trafaret/llms.txt This snippet demonstrates how to use Trafaret's built-in validators for common internet data formats. It includes validation for standard and internationalized emails, URLs, IPv4, IPv6, and a general IP validator. Error handling for invalid formats is also shown. ```python import trafaret as t # Email validation (supports internationalized domain names) email_validator = t.Email result = email_validator.check('user@example.com') # Returns: 'user@example.com' result = email_validator.check('test@münchen.de') # Returns: 'test@münchen.de' try: email_validator.check('invalid-email') except t.DataError as e: print(t.extract_error(email_validator, 'invalid-email')) # 'value is not a valid email address' # URL validation url_validator = t.URL result = url_validator.check('https://example.com') # Returns: 'https://example.com' result = url_validator.check('http://localhost:8080/path') # Returns: 'http://localhost:8080/path' # IPv4 validation ipv4_validator = t.IPv4 result = ipv4_validator.check('192.168.1.1') # Returns: '192.168.1.1' # IPv6 validation ipv6_validator = t.IPv6 result = ipv6_validator.check('2001:0db8::1') # Returns: '2001:0db8::1' # IP validation (accepts both IPv4 and IPv6) ip_validator = t.IP result = ip_validator.check('192.168.1.1') # Returns: '192.168.1.1' result = ip_validator.check('::1') # Returns: '::1' # Hex and URLSafe strings hex_validator = t.Hex() result = hex_validator.check('deadbeef') # Returns: 'deadbeef' urlsafe_validator = t.URLSafe() result = urlsafe_validator.check('safe-URL_123') # Returns: 'safe-URL_123' ``` -------------------------------- ### Sending Data to API Endpoint (Python) Source: https://github.com/deepwalker/trafaret/blob/master/docs/web_use.rst This Python snippet demonstrates how to send JSON data to a local API endpoint using the `requests` library. It includes a sample data dictionary and makes a PUT request, showing how a validation error might be returned from the server. ```python import requests as r data = { "bookTitle": "Glue", "bookPageCount": 436, "bookDescription": "Glue tells the stories of four Scottish boys over four decades...", "bookPrice": 423, "bookFirstAuthor": "Welsh", "bookAuthors": ["Welsh"] } r.put("http://0.0.0.0:8000/", json=data).text # '{"errors": {"id": "is required"}}' ``` -------------------------------- ### Python: Allow extra keys in dictionary validation Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Illustrates how to use the `allow_extra` method of `trafaret.Dict` to permit unexpected keys in a dictionary during validation. It shows validation with all extra keys allowed and with specific extra keys permitted. ```python import trafaret as t data = {'username': 'Misha', 'age': 12, 'email': 'm@gmail.com', 'is_superuser': True} user_validator = t.Dict({'username': t.String, 'age': t.Int}) # generate a new checker with allow any extra keys new_user_validator = user_validator.allow_extra('*') new_user_validator.check(data) ``` ```python import trafaret as t data = {'username': 'Misha', 'age': 12, 'email': 'm@gmail.com', 'is_superuser': True} user_validator = t.Dict({'username': t.String, 'age': t.Int}) # allow only some concretical kyes user_validator.allow_extra('email', 'is_superuser') ``` ```python import trafaret as t data = {'username': 'Misha', 'age': 12, 'email': 'm@gmail.com', 'is_superuser': True} user_validator = t.Dict({'username': t.String, 'age': t.Int}) # specify type of extra keys user_validator.allow_extra('email', 'is_superuser', trafaret=t.String) ``` ```python import trafaret as t # specify extra keys when creating Dict checker user_validator = t.Dict({'username': t.String, 'age': t.Int}, allow_extra=['*']) ``` -------------------------------- ### Validate and Convert to DateTime with Python Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst The DateTime checker validates input against a specified format for datetime.datetime objects. The ToDateTime checker behaves similarly but also returns a datetime.datetime object. ```python DateTime('%Y-%m-%d %H:%M').check("2019-07-25 21:45") # '2019-07-25 21:45' t.extract_error(t.DateTime(), date.today()) # 'value cannot be converted to datetime' DateTime('%Y-%m-%d %H:%M').check("2019-07-25 21:45") # datetime.datetime(2019, 7, 25, 21, 45) ``` -------------------------------- ### Python: Subdict for Dependent Validations Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Explains the 'subdict' functionality for validating related fields, such as passwords and their confirmation. It allows defining a custom validation function that operates on a subset of the data, ensuring consistency between dependent values. ```python from trafaret.keys import subdict def check_passwords_equal(data): if data['password'] != data['password_confirm']: return t.DataError('Passwords are not equal') return data['password'] passwords_key = subdict( 'password', t.Key('password', trafaret=t.String(max_length=10)), t.Key('password_confirm', trafaret=t.String(max_length=10)), trafaret=check_passwords_equal, ) signup_trafaret = t.Dict( t.Key('email', trafaret=t.Email), passwords_key, ) signup_trafaret.check({ "email": "m@gmail.com", "password": "111", "password_confirm": "111", }) # {'email': 'm@gmail.com', 'password': '111'} ``` -------------------------------- ### Trafaret Schema for Creating Books with Custom Type Conversion Source: https://github.com/deepwalker/trafaret/blob/master/docs/web_use.rst Defines a trafaret schema for creating book data, including a custom function `comma_to_list` to convert comma-separated strings into lists and `StrBool` for boolean string conversion. This is useful for handling form data. ```python import trafaret as t def comma_to_list(text): """Convert string with words separated by comma to list.""" return [ s.strip() for s in text.split(',') ] create_book_chacker = t.Dict({ 'title': t.String, 'authors': comma_to_list, 'sold': t.StrBool, }) ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Python: Define dictionary with specific keys and types using Trafaret Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Defines a dictionary structure with specific keys like 'userPassword', 'userEmail', 'userTitle', and 'userRoles'. It specifies the type or transformation for each key, such as hashing for passwords, string for emails, default string for titles, and a comma-separated list for roles. This snippet showcases how to configure custom key mappings and transformations within a Trafaret dictionary. ```python t.Key('userPassword', to_name='password', trafaret=hash_md5), t.Key('userEmail', optional=True, to_name='email', trafaret=t.String), t.Key('userTitle', default='Bachelor', to_name='title', trafaret=t.String), t.Key('userRoles', to_name='roles', trafaret=comma_to_list), ) ``` -------------------------------- ### Python: Guard Decorator for Function Argument Validation Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst Demonstrates the '@t.guard' decorator for validating and transforming function arguments. It allows specifying type checks and conversions for parameters, ensuring that functions receive data in the expected format and raising errors for invalid inputs. ```python @t.guard(user_name=t.String(max_length=10), age=t.ToInt, is_superuser=t.Bool) def create_user(user_name, age, is_superuser=False): # do some stuff ... return (user_name, age, is_superuser) create_user('Misha', '12') # ('Misha', 12, False) # convert age to integer ``` -------------------------------- ### Untitled No description -------------------------------- ### Validate and Convert to Date with Python Source: https://github.com/deepwalker/trafaret/blob/master/docs/intro.rst The Date checker ensures the input is a datetime.date object. It can parse date strings based on a specified format and can also convert compatible types to datetime.date objects using ToDate. ```python t.Date().check("2019-07-25") # '2019-07-25' t.Date().check(date.today()) # datetime.date('2019-07-25') t.Date(format='%y-%m-%d').check('00-01-01') # '00-01-01' t.ToDate().check("2019-07-25") # datetime.date('2019-07-25') ``` -------------------------------- ### Untitled No description -------------------------------- ### Combine Trafaret Validators with Or, And, and Forward Source: https://context7.com/deepwalker/trafaret/llms.txt This snippet illustrates how to construct complex validation logic by combining simpler Trafaret validators. It demonstrates the use of the 'Or' operator for accepting multiple types, the 'And' operator for chaining transformations, and the 'Forward' operator for defining recursive data structures. ```python import trafaret as t import datetime from time import gmtime # Or operator - accept multiple types number_or_string = t.Int() | t.String() result = number_or_string.check(42) # Returns: 42 result = number_or_string.check('hello') # Returns: 'hello' # Class-level Or operator validator = t.Int | t.String | t.Null result = validator.check(None) # Returns: None # And operator - chain transformations converter = t.String() & str.upper result = converter.check('hello') # Returns: 'HELLO' # Rshift operator - pipeline transformations timestamp_to_date = t.Int() >> (lambda ts: datetime.datetime(*gmtime(ts)[:5])) result = timestamp_to_date.check(1234234234) # Returns: datetime.datetime(2009, 2, 10, 2, 10) # Complex chaining validator = t.Regexp(r'^\d+$') & t.ToInt() & (lambda x: x * 2) result = validator.check('21') # Returns: 42 # Forward for recursive structures node_validator = t.Forward() node_validator << t.Dict({ 'value': t.Int(), t.Key('children', optional=True): t.List(node_validator) }) result = node_validator.check({ 'value': 1, 'children': [ {'value': 2}, {'value': 3, 'children': [{'value': 4}]} ] }) ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description