Ultimate transformation library that supports validation, contexts and aiohttp.

Related tags

Networkingtrafaret
Overview

Trafaret

Build status @ Circle CI Gitter Chat Latest release BSD license

Ultimate transformation library that supports validation, contexts and aiohttp.

Trafaret is rigid and powerful lib to work with foreign data, configs etc. It provides simple way to check anything, and convert it accordingly to your needs.

It has shortcut syntax and ability to express anything that you can code:

", line 1, in File "/Users/mkrivushin/w/trafaret/trafaret/__init__.py", line 204, in __call__ return self.check(val) File "/Users/mkrivushin/w/trafaret/trafaret/__init__.py", line 144, in check return self._convert(self.check_and_return(value)) File "/Users/mkrivushin/w/trafaret/trafaret/__init__.py", line 1105, in check_and_return raise DataError(error=errors, trafaret=self) trafaret.DataError: {'b': DataError({1: DataError(value is not a string)})}">
>>> from trafaret.constructor import construct
>>> validator = construct({'a': int, 'b': [str]})
>>> validator({'a': 5, 'b': ['lorem', 'ipsum']})
{'a': 5, 'b': ['lorem', 'ipsum']}

>>> validator({'a': 5, 'b': ['gorky', 9]})
Traceback (most recent call last):
  File "
     
      "
     , line 1, in <module>
  File "/Users/mkrivushin/w/trafaret/trafaret/__init__.py", line 204, in __call__
    return self.check(val)
  File "/Users/mkrivushin/w/trafaret/trafaret/__init__.py", line 144, in check
    return self._convert(self.check_and_return(value))
  File "/Users/mkrivushin/w/trafaret/trafaret/__init__.py", line 1105, in check_and_return
    raise DataError(error=errors, trafaret=self)
trafaret.DataError: {'b': DataError({1: DataError(value is not a string)})}

Read The Docs hosted documentation http://trafaret.readthedocs.org/en/latest/ or look to the docs/intro.rst for start.

Trafaret can even generate Trafarets instances to build transformators from json, like in json schema implementation Trafaret Schema

New

2.0.2

  • construct for int and float will use ToInt and ToFloat

2.0.0

  • WithRepr – use it to return custom representation, like
  • Strip a lot from dict, like keys()
  • Trafarets are not mutable
  • DataError has new code attribute, self.failure has code argument
  • OnError has code argument too
  • New DataError.to_struct method that returns errors in more consistent way
  • String, AnyString, Bytes, FromBytes(encoding=utf-8)
  • Int, ToInt, Float, ToFloat
  • ToDecimal
  • Iterable that acts like a List, but works with any iterable
  • New Date, ToDate and DateTime, ToDateTime trafarets
  • StrBool trafaret renamed to ToBool
  • Visitor trafaret was deleted
  • Test coverage

1.x.x

  • converters and convert=False are deleted in favor of And and &
  • String parameter regex deleted in favor of Regexp and RegexpRaw usage
  • new OnError to customize error message
  • context=something argument for __call__ and check Trafaret methods. Supported by Or, And, Forward etc.
  • new customizable method transform like change_and_return but takes context= arg
  • new trafaret_instance.async_check method that works with await

Doc

For simple example what can be done:

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)

Work with regex:

>>> c = t.RegexpRaw(r'^name=(\w+)$') >> (lambda m: m.group(1))
>>> c.check('name=Jeff')
'Jeff'

Rename dict keys:

>>> c = t.Dict({(t.Key('uNJ') >> 'user_name'): t.String})
>>> c.check({'uNJ': 'Adam'})
{'user_name': 'Adam'}

Arrow date checking:

import arrow

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')

Yes, you can write trafarets that simple.

Related projects

Trafaret Config

Trafaret Validator

Comments
  • SyntaxError on python 3.5

    SyntaxError on python 3.5

    Upgraded to 0.11 and seeing a SyntaxError:

    File "/home/foo/.virtualenvs/bar/lib/python3.5/site-packages/trafaret_config/__init__.py", line 3, in <module>
        from .simple import read_and_validate, parse_and_validate
      File "/home/foo/.virtualenvs/bar/lib/python3.5/site-packages/trafaret_config/simple.py", line 4, in <module>
        import trafaret as _trafaret
      File "/home/foo/.virtualenvs/bar/lib/python3.5/site-packages/trafaret/__init__.py", line 1, in <module>
        from .base import (
      File "/home/foo/.virtualenvs/bar/lib/python3.5/site-packages/trafaret/base.py", line 20, in <module>
        from .async import (
      File "/home/foo/.virtualenvs/bar/lib/python3.5/site-packages/trafaret/async.py", line 176
        yield (
        ^
    SyntaxError: 'yield' inside async function
    
    opened by thijstriemstra 8
  • Need to correct error message for Bytes checker

    Need to correct error message for Bytes checker

    In [19]: t.Bytes().check(b'test') 
    Out[19]: b'test'
    
    In [18]: t.Bytes().check('test')
    ... 
    DataError: value is not a string
    

    In my opinion we need to change string to bytes string.

    opened by Arfey 7
  • Trafaret object to pass value as is

    Trafaret object to pass value as is

    Hello and thank you for your work fiirst of all.

    I have a small suggestion to use trafaret in more uniform way. I have some data with assigned trafaret and some without constraints. So I have to do something like this: if data.trafaret: val = data.trafaret.check_and_return(rawval) else: val = rawval

    If you'll kindly add an object something like "NoCheck" which will pass arguments out without any check it will be possible to always do: val = data.trafaret.check_and_return(rawval)

    while data without constraints will be initialized as: data.trafaret = trafaret.NoCheck()

    opened by ant5 6
  • inner trafaret validation should be called via __call__ method

    inner trafaret validation should be called via __call__ method

    Basic trafarets should be called directly, instead of calling check method.

    Reason: method __call__ is an entrypoint to trafaret

    If we need to redefine method __call__ in custom trafaret, and use this trafaret in t.Or or any other containers, then its method __call__ will never be called.

    Example:

    import trafaret as t
    
    class CustomString(t.String):
        def __call__(self, val, context=None):
            print('hello')
            return super().__call__(val, context)
    
    
    Example = t.Or(CustomString(), t.Int())
    Example('foo')
    

    hello wil never be printed

    opened by litwisha 6
  • `extras.py` is still present on version 2.0.0

    `extras.py` is still present on version 2.0.0

    Steps to reproduce: install latest version from pypi

    image

    There is no extras.py in source code anymore but it is still present after installation. This creates certain confusion as two versions of KeysSubset are present (in keys.py and extras). Moreover, documentation is still pointing to the extras, which is even more confusing

    opened by azhpushkin 5
  • Too old to be a <1.0.0 release version

    Too old to be a <1.0.0 release version

    I'd like to rely on this software for important world changing projects, but it's still in 0.X version which means minor version bumps include breaking changes which is not good.

    Are there any plans to bump to 1.X so I can pin to trafaret>=1,<2? I'd like some sort of agreement of stability before I include start using this to change the world.

    opened by tim-win 5
  • `construct(dict)` doesn't convert types

    `construct(dict)` doesn't convert types

    I'm not sure if it's the intended behavior, but in 0.12 it worked without wrapping into t.Dict:

    >>> rule, raw = {"foo": int}, {"foo": "1"}
    >>> construct(rule)(raw)
    {'foo': '1'}
    >>> construct(t.Dict(rule))(raw)
    {'foo': 1}
    
    opened by imbolc 4
  • Add documentation about Iterable

    Add documentation about Iterable

    In version2 (branch) u need to add to introduction part documentation about Iterable.

    For that u can use tests which connected with current part. As example u can use this PR.

    Please don't forget:

    • your MR u need to do to the version2 (branch)
    • add screenshot with your part of documentation
    • write below that u want to take it to work
    help wanted good first issue 
    opened by Arfey 4
  • DeprecationWarning on import of abstract classes from collections

    DeprecationWarning on import of abstract classes from collections

    In python 3.7 I'm getting the following deprecation warning:

    DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
    

    collections.abc is available starting from python 3.3.

    Are there any plans on fixing it? (I guess you want to retain python2 support yet)

    Also I don't mind to create PR to fix this. If you agree, do you have any preferred way this to be done?

    opened by fly 4
  • Casting one element to a list

    Casting one element to a list

    Sorry for disturbing again.

    I wonder is it possible to convet individually supplied value to a list.

    I want to do something like: t = trafaret.List(trafaret.String()) t(['a','b'])

    ['a','b'] t('a') ['a']

    It will be amazingly cosily to pass FieldStorage.getvalue() directly to trafaret.

    opened by ant5 4
  • Add documentation about Enum

    Add documentation about Enum

    In version2 (branch) u need to add to introduction part documentation about Enum.

    For that u can use old documentation and also tests which connected with current part. As example u can use this PR.

    In this task i recommend to add some example of usage and some reach description.

    Please don't forget:

    • your MR u need to do to the version2 (branch)
    • add screenshot with your part of documentation
    • write below that u want to take it to work
    help wanted good first issue 
    opened by Arfey 3
  • Add type stubs

    Add type stubs

    When importing trafaret from a type-checked codebase, it often generates type check failures (mypy) due to missing explicit __rshift__() method declaration and -> NoReturn for the Trafaret._failure() method.

    I'm currently workarounding the issue by adding a custom stubs: https://github.com/lablup/backend.ai-common/tree/main/stubs/trafaret

    It would be nice if we could embed the type stubs or provide a separate type stubs package. You may start from my privately written type stubs.

    For details about writing/distributing type stubs, refer PEP-561.

    opened by achimnol 2
  • guard don't work correct with keyword-only arguments and default value

    guard don't work correct with keyword-only arguments and default value

    import trafaret as trf
    
    
    @trf.guard(a=trf.Int)
    def foo(*, a=1):
        pass
    
    
    foo()
    
    # GuardError: {'a': DataError('is required')}
    

    problem related to defaults property from FullArgSpec class

    def foo(*, a=1): pass
    def bar(a=1): pass
    
    getargspec(foo)
    # FullArgSpec(args=[], varargs=None, varkw=None, defaults=None, kwonlyargs=['a'], kwonlydefaults={'a': 1}, annotations={})
    
    getargspec(bar)
    # FullArgSpec(args=['a'], varargs=None, varkw=None, defaults=(1,), kwonlyargs=[], kwonlydefaults=None, annotations={})
    

    https://github.com/Deepwalker/trafaret/blob/master/trafaret/base.py#L1493-L1496

    here we need try to use the kwonlydefaults mapping

    help wanted 
    opened by Arfey 3
  • Support for Set in addition to List and Tuple?

    Support for Set in addition to List and Tuple?

    Hi, thanks for the useful package!

    Is there any technical reason behind Set support absence?

    Or I'm a very first person who actually needs it?

    If it's missed because no one needs it yet, and maintainers are not against it, I would like to provide pull request with such implementation. Documentation and tests included.

    Hopefully, new minor release would be issued after this contribution.

    Thoughts?

    Regards, Artem.

    opened by proofit404 3
  • Generate JSON schema from trafarets

    Generate JSON schema from trafarets

    Hi,

    Would it be possible to generate a JSON schema (https://json-schema.org/) from the trafaret definition? This would be really useful because the schema can be used in the IDE (vscode in my case) to autocomplete the yaml file as you are typing (https://github.com/redhat-developer/yaml-language-server). Any thoughts on this?

    opened by ErikOrjehag 4
  • Avoid checking default values

    Avoid checking default values

    When using a default value such as: t.Key("integration", default=None, trafaret=t.Regexp(r"\w+"))

    This will result in an error, as it checks the default argument against the trafaret object. It seems sensible to skip any checking of the default argument for efficiency and to allow code as shown above.

    opened by Dreamsorcerer 0
Releases(v2.0.2)
DataShare - Simple library for data sharing between scripts and public functions calling

DataShare - Simple library for data sharing between scripts and public functions calling. Installation. Install code, Delete LICENSE, README, readme.t

Ivan Perzhinsky. 1 Dec 17, 2021
PcapXray - A Network Forensics Tool - To visualize a Packet Capture offline as a Network Diagram

PcapXray - A Network Forensics Tool - To visualize a Packet Capture offline as a Network Diagram including device identification, highlight important communication and file extraction

Srinivas P G 1.4k Dec 28, 2022
Godzilla traffic decoder Godzilla Decoder 是一个用于 哥斯拉Godzilla 加密流量分析的辅助脚本。

Godzilla Decoder 简介 Godzilla Decoder 是一个用于 哥斯拉Godzilla 加密流量分析的辅助脚本。 Godzilla Decoder 基于 mitmproxy,是mitmproxy的addon脚本。 目前支持 哥斯拉3.0.3 PhpDynamicPayload的

He Ruiliang 40 Dec 25, 2022
Simple HTTP Server for CircuitPython

Introduction Simple HTTP Server for CircuitPython Dependencies This driver depen

Adafruit Industries 22 Jan 06, 2023
Juniper SNMP Migrations For Python

Juniper SNMP Migrations This example will show how to use the PyEZ plugin for Nornir to build a NETCONF connection to a remote device validate that SN

Calvin Remsburg 1 Jan 07, 2022
A socket script to obtain chinese phones-sequence for any english word

Foreign Pronunciation Generator (English-Chinese) We provide a simple socket script for acquiring Chinese pronunciation of English words (phones in ai

Ephemeroptera 5 Jul 25, 2022
Implementing Cisco Support APIs into NetBox

NetBox Cisco Support API Plugin NetBox plugin using Cisco Support APIs to gather EoX and Contract coverage information for Cisco devices. Compatibilit

Timo Reimann 23 Dec 21, 2022
Proxlist - Retrieve proxy servers.

Finding and storing a list of proxies can be taxing - especially ones that are free and may not work only minutes from now. proxlist will validate the proxy and return a rotating random proxy to you

Justin Hammond 2 Mar 17, 2022
Interact remotely with the computer using Python and MQTT protocol 💻

Comandos_Remotos Interagir remotamento com o computador através do Python e protocolo MQTT. 💻 Status: em desenvolvimento 🚦 Objetivo: Interagir com o

Guilherme_Donizetti 6 May 10, 2022
This Tool Help To Information gathering for domain name or ip address...

Owl-Eye This Tool Help To Information gathering for domain name or ip address... follow this command $apt update && upgrade $apt install python apt in

Black Owl 6 Nov 12, 2022
Transfer files to and from a Windows host via ICMP in restricted network environments.

ICMP-TransferTools ICMP-TransferTools is a set of scripts designed to move files to and from Windows hosts in restricted network environments. This is

icyguider 269 Dec 20, 2022
ServerStatus with node management and monitor

ServerStatus with node management and monitor

lidalao 162 Jan 01, 2023
netpy - more than implementation of netcat 🐍🔥

netpy - more than implementation of netcat 🐍🔥

Mahmoud S. ElGammal 1 Jan 26, 2022
A python tool auto change proxy or ip after dealy time set by user

Auto proxy Ghost This tool auto change proxy or ip after dealy time set by user how to run 1. Install required file ./requirements.sh 2.Enter command

Harsh Tagra 0 Feb 23, 2022
A Network tool kit for scanning active IP addresses and open ports

Network scanner A small project that I wrote on the fly for (IT351) Computer Networks University Course to identify and label the devices in my networ

Mohamed Abdelrahman 10 Nov 07, 2022
Cobalt Strike C2 Reverse proxy that fends off Blue Teams, AVs, EDRs, scanners through packet inspection and malleable profile correlation

Cobalt Strike C2 Reverse proxy that fends off Blue Teams, AVs, EDRs, scanners through packet inspection and malleable profile correlation

Mariusz B. 715 Dec 25, 2022
Web service load balancing simulation experiment.

Web service load balancing simulation experiment.

NicestZK 1 Nov 12, 2021
RabbitMQ asynchronous connector library for Python with built in RPC support

About RabbitMQ connector library for Python that is fully integrated with the aio-pika framework. Introduction BunnyStorm is here to simplify working

22 Sep 11, 2022
Apple Store Stock Notifier monitors the availability of selected Apple devices in selected Apple stores, and sends you a notification when devices are available!

Apple Store Stock Notifier This software will immediately send you a notification via Telegram when one of your coveted Apple Devices is available in

Floris-Jan Willemsen 25 Dec 05, 2022
Socialhome is best described as a federated personal profile with social networking functionality

Description Socialhome is best described as a federated personal profile with social networking functionality. Users can create rich content using Mar

Jason Robinson 332 Dec 30, 2022