trafaret


Nametrafaret JSON
Version 2.1.1 PyPI version JSON
download
home_pagehttps://github.com/Deepwalker/trafaret/
SummaryValidation and parsing library
upload_time2022-04-01 17:36:25
maintainerNone
docs_urlNone
authorBarbuza, Deepwalker, nimnull
requires_pythonNone
licenseBSD
keywords validation form forms data schema
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage
            Trafaret
========

|circleci_build| |gitter_chat| |pypi_version| |pypi_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:

.. code-block:: python

    >>> 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 <https://github.com/Deepwalker/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:

.. code-block:: 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)

Work with regex:

.. code-block:: python

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

Rename dict keys:

.. code-block:: python

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

``Arrow`` date checking:

.. code-block:: python

    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 <https://github.com/tailhook/trafaret-config>`_

`Trafaret Validator <https://github.com/Lex0ne/trafaret_validator>`_


.. _docs/intro.rst: docs/intro.rst

.. |circleci_build| image:: https://circleci.com/gh/Deepwalker/trafaret.svg?style=shield
    :target: https://circleci.com/gh/Deepwalker/trafaret
    :alt: Build status @ Circle CI

.. |gitter_chat| image:: https://badges.gitter.im/Deepwalker/trafaret.svg
    :target: https://gitter.im/Deepwalker/trafaret
    :alt: Gitter Chat

.. |pypi_version| image:: https://img.shields.io/pypi/v/trafaret.svg?style=flat-square
    :target: https://pypi.org/p/trafaret
    :alt: Latest release

.. |pypi_license| image:: https://img.shields.io/pypi/l/trafaret.svg?style=flat-square
    :target: https://pypi.python.org/pypi/trafaret
    :alt: BSD license

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Deepwalker/trafaret/",
    "name": "trafaret",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "validation form forms data schema",
    "author": "Barbuza, Deepwalker, nimnull",
    "author_email": "krivushinme@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/c9/ed/aac034e566f8846aee6472dcc90da6011a0b1829e3ffc768407df519a3b0/trafaret-2.1.1.tar.gz",
    "platform": null,
    "description": "Trafaret\n========\n\n|circleci_build| |gitter_chat| |pypi_version| |pypi_license|\n\nUltimate transformation library that supports validation, contexts and ``aiohttp``.\n\nTrafaret is rigid and powerful lib to work with foreign data, configs etc.\nIt provides simple way to check anything, and convert it accordingly to your needs.\n\nIt has shortcut syntax and ability to express anything that you can code:\n\n.. code-block:: python\n\n    >>> from trafaret.constructor import construct\n    >>> validator = construct({'a': int, 'b': [str]})\n    >>> validator({'a': 5, 'b': ['lorem', 'ipsum']})\n    {'a': 5, 'b': ['lorem', 'ipsum']}\n\n    >>> validator({'a': 5, 'b': ['gorky', 9]})\n    Traceback (most recent call last):\n      File \"<console>\", line 1, in <module>\n      File \"/Users/mkrivushin/w/trafaret/trafaret/__init__.py\", line 204, in __call__\n        return self.check(val)\n      File \"/Users/mkrivushin/w/trafaret/trafaret/__init__.py\", line 144, in check\n        return self._convert(self.check_and_return(value))\n      File \"/Users/mkrivushin/w/trafaret/trafaret/__init__.py\", line 1105, in check_and_return\n        raise DataError(error=errors, trafaret=self)\n    trafaret.DataError: {'b': DataError({1: DataError(value is not a string)})}\n\n\nRead The Docs hosted documentation http://trafaret.readthedocs.org/en/latest/\nor look to the `docs/intro.rst`_ for start.\n\nTrafaret can even generate Trafarets instances to build transformators from json,\nlike in json schema implementation `Trafaret Schema <https://github.com/Deepwalker/trafaret_schema>`_\n\n\nNew\n---\n\n2.0.2\n=====\n- construct for `int` and `float` will use `ToInt` and `ToFloat`\n\n2.0.0\n=====\n\n- ``WithRepr`` \u2013 use it to return custom representation, like ``<Email>``\n- Strip a lot from dict, like ``keys()``\n- Trafarets are not mutable\n- DataError has new ``code`` attribute, self.failure has ``code`` argument\n- OnError has ``code`` argument too\n- New ``DataError.to_struct`` method that returns errors in more consistent way\n- ``String``, ``AnyString``, ``Bytes``, ``FromBytes(encoding=utf-8)``\n- ``Int``, ``ToInt``, ``Float``, ``ToFloat``\n- ``ToDecimal``\n- ``Iterable`` that acts like a ``List``, but works with any iterable\n- New ``Date``, ``ToDate`` and ``DateTime``, ``ToDateTime`` trafarets\n- ``StrBool`` trafaret renamed to ``ToBool``\n- ``Visitor`` trafaret was deleted\n- Test coverage\n\n1.x.x\n=====\n\n* converters and ``convert=False`` are deleted in favor of ``And`` and ``&``\n* ``String`` parameter ``regex`` deleted in favor of ``Regexp`` and ``RegexpRaw`` usage\n* new ``OnError`` to customize error message\n* ``context=something`` argument for ``__call__`` and ``check`` Trafaret methods.\n  Supported by ``Or``, ``And``, ``Forward`` etc.\n* new customizable method ``transform`` like ``change_and_return`` but takes ``context=`` arg\n* new ``trafaret_instance.async_check`` method that works with ``await``\n\nDoc\n---\n\nFor simple example what can be done:\n\n.. code-block:: python\n\n    import datetime\n    import trafaret as t\n\n    date = t.Dict(year=t.Int, month=t.Int, day=t.Int) >> (lambda d: datetime.datetime(**d))\n    assert date.check({'year': 2012, 'month': 1, 'day': 12}) == datetime.datetime(2012, 1, 12)\n\nWork with regex:\n\n.. code-block:: python\n\n    >>> c = t.RegexpRaw(r'^name=(\\w+)$') >> (lambda m: m.group(1))\n    >>> c.check('name=Jeff')\n    'Jeff'\n\nRename dict keys:\n\n.. code-block:: python\n\n    >>> c = t.Dict({(t.Key('uNJ') >> 'user_name'): t.String})\n    >>> c.check({'uNJ': 'Adam'})\n    {'user_name': 'Adam'}\n\n``Arrow`` date checking:\n\n.. code-block:: python\n\n    import arrow\n\n    def check_datetime(str):\n        try:\n            return arrow.get(str).naive\n        except arrow.parser.ParserError:\n            return t.DataError('value is not in proper date/time format')\n\nYes, you can write trafarets that simple.\n\n\nRelated projects\n----------------\n\n`Trafaret Config <https://github.com/tailhook/trafaret-config>`_\n\n`Trafaret Validator <https://github.com/Lex0ne/trafaret_validator>`_\n\n\n.. _docs/intro.rst: docs/intro.rst\n\n.. |circleci_build| image:: https://circleci.com/gh/Deepwalker/trafaret.svg?style=shield\n    :target: https://circleci.com/gh/Deepwalker/trafaret\n    :alt: Build status @ Circle CI\n\n.. |gitter_chat| image:: https://badges.gitter.im/Deepwalker/trafaret.svg\n    :target: https://gitter.im/Deepwalker/trafaret\n    :alt: Gitter Chat\n\n.. |pypi_version| image:: https://img.shields.io/pypi/v/trafaret.svg?style=flat-square\n    :target: https://pypi.org/p/trafaret\n    :alt: Latest release\n\n.. |pypi_license| image:: https://img.shields.io/pypi/l/trafaret.svg?style=flat-square\n    :target: https://pypi.python.org/pypi/trafaret\n    :alt: BSD license\n",
    "bugtrack_url": null,
    "license": "BSD",
    "summary": "Validation and parsing library",
    "version": "2.1.1",
    "split_keywords": [
        "validation",
        "form",
        "forms",
        "data",
        "schema"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "45511a9759b923aecd459417609fffd6",
                "sha256": "1966f432586797aed663edd54cbc201fd7ba59eed1638f1a7a33f17977b3a569"
            },
            "downloads": -1,
            "filename": "trafaret-2.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "45511a9759b923aecd459417609fffd6",
            "packagetype": "bdist_wheel",
            "python_version": "3.7",
            "requires_python": null,
            "size": 28399,
            "upload_time": "2022-04-01T17:36:29",
            "upload_time_iso_8601": "2022-04-01T17:36:29.066227Z",
            "url": "https://files.pythonhosted.org/packages/64/32/17b47745df926eff2e5b89d79838337de88258f65a936f70416a15190142/trafaret-2.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "85085fe18dd133d3622a2f7a3b0acf6a",
                "sha256": "d9d00800318fbd343fdfb3353e947b2ebb5557159c844696c5ac24846f76d41c"
            },
            "downloads": -1,
            "filename": "trafaret-2.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "85085fe18dd133d3622a2f7a3b0acf6a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 26249,
            "upload_time": "2022-04-01T17:36:25",
            "upload_time_iso_8601": "2022-04-01T17:36:25.910287Z",
            "url": "https://files.pythonhosted.org/packages/c9/ed/aac034e566f8846aee6472dcc90da6011a0b1829e3ffc768407df519a3b0/trafaret-2.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2022-04-01 17:36:25",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "Deepwalker",
    "github_project": "trafaret",
    "travis_ci": true,
    "coveralls": true,
    "github_actions": false,
    "circle": true,
    "tox": true,
    "lcname": "trafaret"
}
        
Elapsed time: 0.03649s