Skip to main content

Validation and parsing library

Project description

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:

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

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 <Email>

  • 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.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

trafaret-2.0.2.tar.gz (25.6 kB view details)

Uploaded Source

Built Distribution

trafaret-2.0.2-py3-none-any.whl (27.8 kB view details)

Uploaded Python 3

File details

Details for the file trafaret-2.0.2.tar.gz.

File metadata

  • Download URL: trafaret-2.0.2.tar.gz
  • Upload date:
  • Size: 25.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: Python-urllib/3.6

File hashes

Hashes for trafaret-2.0.2.tar.gz
Algorithm Hash digest
SHA256 61dfc25b574f70bfdf7ee3a808ec423061811c13a10b8d3c9e11ab539b96ab65
MD5 c840b97f3d96627f0655240776fa69be
BLAKE2b-256 be4c659368a41323a1597b2bc973c8ec5ebe4a0d0b6bd141f081674f0db6e90f

See more details on using hashes here.

File details

Details for the file trafaret-2.0.2-py3-none-any.whl.

File metadata

  • Download URL: trafaret-2.0.2-py3-none-any.whl
  • Upload date:
  • Size: 27.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: Python-urllib/3.6

File hashes

Hashes for trafaret-2.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 5d560577cb7f5ec015cdb9298e46ec07fd9e0224bc0aaecc7d0fa0e92ea251d9
MD5 8afbeb777e4d53a3902352fa4bf26bc0
BLAKE2b-256 cb3f3c7f8845d854763475daeeaa9b934fa568c153c56c932d61e71b4b39c7bb

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page