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:
>>> 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 "<console>", 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
- construct for int and float will use ToInt and ToFloat
WithRepr– use it to return custom representation, like<Email>- Strip a lot from dict, like
keys() - Trafarets are not mutable
- DataError has new
codeattribute, self.failure hascodeargument - OnError has
codeargument too - New
DataError.to_structmethod that returns errors in more consistent way String,AnyString,Bytes,FromBytes(encoding=utf-8)Int,ToInt,Float,ToFloatToDecimalIterablethat acts like aList, but works with any iterable- New
Date,ToDateandDateTime,ToDateTimetrafarets StrBooltrafaret renamed toToBoolVisitortrafaret was deleted- Test coverage
- converters and
convert=Falseare deleted in favor ofAndand& Stringparameterregexdeleted in favor ofRegexpandRegexpRawusage- new
OnErrorto customize error message context=somethingargument for__call__andcheckTrafaret methods. Supported byOr,And,Forwardetc.- new customizable method
transformlikechange_and_returnbut takescontext=arg - new
trafaret_instance.async_checkmethod that works withawait
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.