cerberror


Namecerberror JSON
Version 0.1.1 PyPI version JSON
download
home_pageNone
SummaryA package allowing to define own error messages for Cerberus
upload_time2025-02-15 17:47:30
maintainerNone
docs_urlNone
authorPrzemysław Bruś
requires_python>=3.7
licenseMIT License Copyright (c) 2020 Przemysław Bruś Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords validation customized error messages
VCS
bugtrack_url
requirements Cerberus
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Cerberror
![tests](https://github.com/pbrus/cerberror/actions/workflows/ci.yml/badge.svg?branch=master)
[![Python](https://img.shields.io/badge/Python-%203.10%20|%203.11%20|%203.12%20|%203.13%20-blue.svg "Python")](https://www.python.org/)
[![Style](https://img.shields.io/badge/code%20style-Black-black.svg "Black")](https://black.readthedocs.io/en/stable/)
[![License](https://img.shields.io/badge/license-MIT-yellow.svg "MIT license")](https://github.com/pbrus/cerberror/blob/master/LICENSE)

**Cerberror** was designed to customize and handle errors generated by the validator of [Cerberus](https://docs.python-cerberus.org/).

## How it works?

Let's start from checking errors generated by Cerberus:
```python
>>> v = Validator({'params': {'type': 'dict', 'schema': {'var1': {'type': 'integer'}, 'var2': {'allowed': [7, 8, 9]}}}})
>>> v.validate({'params': {'var1': 'Hello World!', 'var2': 3.14}})
>>> v.errors
{'params': [{'var1': ['must be of integer type'], 'var2': ['unallowed value 3.14']}]}
```
At least two problems occur when we want to inform a user what went wrong:
 - predetermined error messages,
 - unclear path to wrong variable.

 Let's define new messages in `msgs.txt` file:
 ```
 ('params', 'var1') 36 "{{value}} is not an integer!"
 ('params', 'var2') 68 "{{value}} not found in {{constraint}}..."
 ```
where the columns contain:
1. A path to the element defined by a tuple. Note that one-element tuple must be defined as `('some_param',)`, not `'some_param',`.
2. An error code from the [API documentation](https://docs.python-cerberus.org/en/stable/api.html#error-codes). A particular path can have many rules which implies many records in `msgs.txt` for that path.
3. A user-defined message. Optionally we can refer to [attributes](https://docs.python-cerberus.org/en/stable/api.html#cerberus.errors.ValidationError) of a particular error using `{{attr}}` expressions. Note that a message must be defined between two `"`, not `'`.

To get new messages we use `Translator` object:
```python
>>> from cerberror import Translator

>>> tr = Translator(v, 'msgs.txt')
>>> tr.translate()
{'params -> var2': ['3.14 not found in [7, 8, 9]...'], 'params -> var1': ['Hello World! is not an integer!']}
```

## Installation

To install the package please type from the command line:
```bash
$ pip3 install cerberror
```

## Features
**Cerberror** has a few features which facilitate the usage of it.
### Updates
Just like the validator of Cerberus, `Translator` object can be updated at any time:
```python
>>> tr = Translator(validator, 'messages.txt')
>>> tr.validator = another_validator
>>> tr.path_to_file = 'another_messages.txt'
```
This feature is particularly useful when we want to update files with messages on the fly. It could be used when we need to change language. Just define a proper file:
```
('params', 'var1') 36 "{{value}} ist keine ganze Zahl!"
('params', 'var2') 68 "{{value}} nicht unter {{constraint}} gefunden..."
```

### Comments
Comments can be added to files with messages. These files are parsing with the usage of the regular expressions. Valid records are those defined in [How it works?](#how-it-works) section. This means that everything else is treated as a comment. However, I recommend to use `#` to mark where they start.
 ```
 # Comment.
 ('params', 'var1') 36 "{{value}} is not an integer!"  # Inline comment.
 ('params', 'var2') 68 "{{value}} not found in {{constraint}}..."
 ```

### Paths
The returned paths are joined with usage of the default value `' -> '`. This behaviour can be changed easily:
```python
>>> tr = Translator(v, 'msgs.txt')
>>> tr.translate('_')
{'params_var2': ['3.14 not found in [7, 8, 9]...'], 'params_var1': ['Hello World! is not an integer!']}
```

### Returns
If the translation will finish successfully, the returned value will be a dictionary composed of `path:message(s)` pairs. Otherwise, `Translator` will return untouched errors generated by Cerberus. We can check the status of the translation using `any_error` property:
```python
>>> tr.any_error
False
>>> tr.errors
{'params -> var2': ['3.14 not found in [7, 8, 9]...'], 'params -> var1': ['Hello World! is not an integer!']}
...
>>> tr.any_error
True
>>> tr.errors
{'params': [{'var1': ['must be of integer type'], 'var2': ['unallowed value 3.14']}]}  # v.errors
```

### Internal errors
Internal errors can be inspected to find out what went wrong. The assumption was that **Cerberror** must not interrupt the translation process. If internal errors occur, `any_error` property will return `True`. Internal errors are always store in `error_list` property. For example:
```
# foo and bar attributes don't exist
('params', 'var1') 36 "{{foo}} is not an integer!"
('params', 'var2') 68 "{{value}} not found in {{bar}}..."
```
```python
>>> tr = Translator(v, 'msgs.txt')
>>> tr.translate()
{'params': [{'var1': ['must be of integer type'], 'var2': ['unallowed value 3.14']}]}
>>> tr.any_error
True
>>> tr.error_list
["Invalid expression '{{bar}}' in file 'msgs.txt'", "Invalid expression '{{foo}}' in file 'msgs.txt'"]
```

## Contribution

New feature, bugs? Issues and pull requests are welcome.

## License

**Cerberror** is licensed under the [MIT license](http://opensource.org/licenses/MIT).

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "cerberror",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "validation, customized, error, messages",
    "author": "Przemys\u0142aw Bru\u015b",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/15/8b/021995fa44982a2e0c4a3fdc5bca024648c3c66b504f4ab0878ecf7b240f/cerberror-0.1.1.tar.gz",
    "platform": null,
    "description": "# Cerberror\n![tests](https://github.com/pbrus/cerberror/actions/workflows/ci.yml/badge.svg?branch=master)\n[![Python](https://img.shields.io/badge/Python-%203.10%20|%203.11%20|%203.12%20|%203.13%20-blue.svg \"Python\")](https://www.python.org/)\n[![Style](https://img.shields.io/badge/code%20style-Black-black.svg \"Black\")](https://black.readthedocs.io/en/stable/)\n[![License](https://img.shields.io/badge/license-MIT-yellow.svg \"MIT license\")](https://github.com/pbrus/cerberror/blob/master/LICENSE)\n\n**Cerberror** was designed to customize and handle errors generated by the validator of [Cerberus](https://docs.python-cerberus.org/).\n\n## How it works?\n\nLet's start from checking errors generated by Cerberus:\n```python\n>>> v = Validator({'params': {'type': 'dict', 'schema': {'var1': {'type': 'integer'}, 'var2': {'allowed': [7, 8, 9]}}}})\n>>> v.validate({'params': {'var1': 'Hello World!', 'var2': 3.14}})\n>>> v.errors\n{'params': [{'var1': ['must be of integer type'], 'var2': ['unallowed value 3.14']}]}\n```\nAt least two problems occur when we want to inform a user what went wrong:\n - predetermined error messages,\n - unclear path to wrong variable.\n\n Let's define new messages in `msgs.txt` file:\n ```\n ('params', 'var1') 36 \"{{value}} is not an integer!\"\n ('params', 'var2') 68 \"{{value}} not found in {{constraint}}...\"\n ```\nwhere the columns contain:\n1. A path to the element defined by a tuple. Note that one-element tuple must be defined as `('some_param',)`, not `'some_param',`.\n2. An error code from the [API documentation](https://docs.python-cerberus.org/en/stable/api.html#error-codes). A particular path can have many rules which implies many records in `msgs.txt` for that path.\n3. A user-defined message. Optionally we can refer to [attributes](https://docs.python-cerberus.org/en/stable/api.html#cerberus.errors.ValidationError) of a particular error using `{{attr}}` expressions. Note that a message must be defined between two `\"`, not `'`.\n\nTo get new messages we use `Translator` object:\n```python\n>>> from cerberror import Translator\n\n>>> tr = Translator(v, 'msgs.txt')\n>>> tr.translate()\n{'params -> var2': ['3.14 not found in [7, 8, 9]...'], 'params -> var1': ['Hello World! is not an integer!']}\n```\n\n## Installation\n\nTo install the package please type from the command line:\n```bash\n$ pip3 install cerberror\n```\n\n## Features\n**Cerberror** has a few features which facilitate the usage of it.\n### Updates\nJust like the validator of Cerberus, `Translator` object can be updated at any time:\n```python\n>>> tr = Translator(validator, 'messages.txt')\n>>> tr.validator = another_validator\n>>> tr.path_to_file = 'another_messages.txt'\n```\nThis feature is particularly useful when we want to update files with messages on the fly. It could be used when we need to change language. Just define a proper file:\n```\n('params', 'var1') 36 \"{{value}} ist keine ganze Zahl!\"\n('params', 'var2') 68 \"{{value}} nicht unter {{constraint}} gefunden...\"\n```\n\n### Comments\nComments can be added to files with messages. These files are parsing with the usage of the regular expressions. Valid records are those defined in [How it works?](#how-it-works) section. This means that everything else is treated as a comment. However, I recommend to use `#` to mark where they start.\n ```\n # Comment.\n ('params', 'var1') 36 \"{{value}} is not an integer!\"  # Inline comment.\n ('params', 'var2') 68 \"{{value}} not found in {{constraint}}...\"\n ```\n\n### Paths\nThe returned paths are joined with usage of the default value `' -> '`. This behaviour can be changed easily:\n```python\n>>> tr = Translator(v, 'msgs.txt')\n>>> tr.translate('_')\n{'params_var2': ['3.14 not found in [7, 8, 9]...'], 'params_var1': ['Hello World! is not an integer!']}\n```\n\n### Returns\nIf the translation will finish successfully, the returned value will be a dictionary composed of `path:message(s)` pairs. Otherwise, `Translator` will return untouched errors generated by Cerberus. We can check the status of the translation using `any_error` property:\n```python\n>>> tr.any_error\nFalse\n>>> tr.errors\n{'params -> var2': ['3.14 not found in [7, 8, 9]...'], 'params -> var1': ['Hello World! is not an integer!']}\n...\n>>> tr.any_error\nTrue\n>>> tr.errors\n{'params': [{'var1': ['must be of integer type'], 'var2': ['unallowed value 3.14']}]}  # v.errors\n```\n\n### Internal errors\nInternal errors can be inspected to find out what went wrong. The assumption was that **Cerberror** must not interrupt the translation process. If internal errors occur, `any_error` property will return `True`. Internal errors are always store in `error_list` property. For example:\n```\n# foo and bar attributes don't exist\n('params', 'var1') 36 \"{{foo}} is not an integer!\"\n('params', 'var2') 68 \"{{value}} not found in {{bar}}...\"\n```\n```python\n>>> tr = Translator(v, 'msgs.txt')\n>>> tr.translate()\n{'params': [{'var1': ['must be of integer type'], 'var2': ['unallowed value 3.14']}]}\n>>> tr.any_error\nTrue\n>>> tr.error_list\n[\"Invalid expression '{{bar}}' in file 'msgs.txt'\", \"Invalid expression '{{foo}}' in file 'msgs.txt'\"]\n```\n\n## Contribution\n\nNew feature, bugs? Issues and pull requests are welcome.\n\n## License\n\n**Cerberror** is licensed under the [MIT license](http://opensource.org/licenses/MIT).\n",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2020 Przemys\u0142aw Bru\u015b\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \"Software\"), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in all\n        copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n        SOFTWARE.\n        ",
    "summary": "A package allowing to define own error messages for Cerberus",
    "version": "0.1.1",
    "project_urls": {
        "Source": "https://github.com/pbrus/cerberror"
    },
    "split_keywords": [
        "validation",
        " customized",
        " error",
        " messages"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "a13814fa29f82f6d1bcc70948238928385ddd3138ff5f7f7646d6d7d73e0d621",
                "md5": "151933e673ac1bcc37cd8f37a1e9bb89",
                "sha256": "82c9c46b38d4a81ff11fef28f31e0c203df2a0ab0739c6c9bcf5e17a47ddeba5"
            },
            "downloads": -1,
            "filename": "cerberror-0.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "151933e673ac1bcc37cd8f37a1e9bb89",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 9129,
            "upload_time": "2025-02-15T17:47:29",
            "upload_time_iso_8601": "2025-02-15T17:47:29.056918Z",
            "url": "https://files.pythonhosted.org/packages/a1/38/14fa29f82f6d1bcc70948238928385ddd3138ff5f7f7646d6d7d73e0d621/cerberror-0.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "158b021995fa44982a2e0c4a3fdc5bca024648c3c66b504f4ab0878ecf7b240f",
                "md5": "49b8be8d5ef7bd35c55322e7fd110989",
                "sha256": "569ee87091a7c69954c0aa88ffa26a38b0b8815e1833520252ce5e75713fcf85"
            },
            "downloads": -1,
            "filename": "cerberror-0.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "49b8be8d5ef7bd35c55322e7fd110989",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 13335,
            "upload_time": "2025-02-15T17:47:30",
            "upload_time_iso_8601": "2025-02-15T17:47:30.950331Z",
            "url": "https://files.pythonhosted.org/packages/15/8b/021995fa44982a2e0c4a3fdc5bca024648c3c66b504f4ab0878ecf7b240f/cerberror-0.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-02-15 17:47:30",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "pbrus",
    "github_project": "cerberror",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "Cerberus",
            "specs": [
                [
                    ">=",
                    "1.3.7"
                ]
            ]
        }
    ],
    "lcname": "cerberror"
}
        
Elapsed time: 0.61310s