============
Simple Model
============
.. image:: https://badge.fury.io/py/pysimplemodel.svg
:target: https://pypi.org/project/pysimplemodel/
.. image:: https://img.shields.io/badge/python-3.6,3.7-blue.svg
:target: https://github.com/lamenezes/simple-model
.. image:: https://img.shields.io/github/license/lamenezes/simple-model.svg
:target: https://github.com/lamenezes/simple-model/blob/master/LICENSE
.. image:: https://circleci.com/gh/lamenezes/simple-model.svg?style=shield
:target: https://circleci.com/gh/lamenezes/simple-model
.. image:: https://codecov.io/gh/lamenezes/simple-model/branch/master/graph/badge.svg
:target: https://codecov.io/gh/lamenezes/simple-model
*SimpleModel* offers a simple way to handle data using classes instead of a
plenty of lists and dicts.
It has simple objectives:
- Define models and its fields easily using class attributes, type annotations or tuples (whatever suits your needs)
- Support for field validation, cleaning and type conversion
- Easy model conversion to dict
Quickstart
==========
Installing
----------
Open your favorite shell and run the following command:
.. code:: shell
pip install pysimplemodel
Example
-------
Define your models using type annotations:
.. code:: python
from simple_model import Model
class Person(Model):
age: int
height: float
is_active: bool = True
name: str
Simple model automatically creates an initializer for your model and you all set
to create instances:
.. code:: python
>> person = Person(age=18, height=1.67, name='John Doe')
>> person.name
'John Doe'
As you have noticed we haven't informed a value for field `is_active`, but the model
was still created. That's because we've set a default value of `True` for it and
the model takes care of assigning it automatically to the field:
.. code:: python
>> person.is_active
True
Simple model also offers model validation. Empty fields are considered invalid and will
raise errors upon validation. Let's perform some tests using the previous `Person` model:
.. code:: python
>> person = Person()
>> print(person.name)
None
>> person.validate()
Traceback (most recent call last):
...
EmptyField: 'height' field cannot be empty
Let's say we want the height and age fields to be optional, that can be achieved with
the following piece of code:
.. code:: python
from simple_model import Model
class Person(Model):
age: int = None
height: float = None
is_active: bool = True
name: str
Now let's test it:
.. code:: python
>> person = Person(name='Jane Doe', is_active=False)
>> person.is_active
False
>> person.validate()
True
The last line won't raise an exception which means the model instance is valid!
In case you need the validation to return True or False instead of raising an
exception that's possible by doing the following:
.. code:: python
>> person.validate(raise_exception=False)
True
You can also add custom validations by writing class methods prefixed by `validate`
followed by the attribute name, e.g.
.. code:: python
class Person:
age: int
height: float
name: str
def validate_age(self, age):
if age < 0 or age > 150:
raise ValidationError('Invalid value for age {!r}'.format(age))
return age
def validate_height(self, height):
if height <= 0:
raise ValidationError('Invalid value for height {!r}'.format(age))
return height
Let's test it:
.. code:: python
>> person = Person(name='John Doe', age=190)
>> person.validate()
Traceback (most recent call last):
...
ValidationError: Invalid value for age 190
>> other_person = Person(name='Jane Doe', height=-1.67)
>> other_person.validate()
Traceback (most recent call last):
...
ValidationError: Invalid value for height -1.67
It is important to note that models don't validate types. Currently types are used
for field value conversion.
The `validate` method also supports cleaning the field values by defining custom transformations
in the `validate_` methods:
.. code:: python
class Person:
age: int
name: str
def validate_name(self, name):
return name.strip()
>>> person = Person(age=18.0, name='John Doe ')
>>> person.name
'John Doe '
>> person.age
18.0
>>> person.validate()
>>> person.name
'John Doe'
>>> person.age # all attributes are converted to its type before cleaning
18 # converted from float (18.0) to int (18)
Finally, simple model allows you to easily convert your model to dict type using the function `to_dict()`:
.. code:: python
>>> to_dict(person)
{
'age': 18,
'name': 'John Doe'
}
Documentation
=============
Docs on simple-model.rtfd.io_
.. _simple-model.rtfd.io: https://simple-model.readthedocs.io/en/latest/
Raw data
{
"_id": null,
"home_page": "https://github.com/lamenezes/simple-model",
"name": "pysimplemodel",
"maintainer": "",
"docs_url": null,
"requires_python": "",
"maintainer_email": "",
"keywords": "",
"author": "Luiz Menezes",
"author_email": "luiz.menezesf@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/d2/6b/5c3f629c95b956b766af81eb61fb54d6bb5d714ef35980e47e06d309080e/pysimplemodel-2.4.3.tar.gz",
"platform": "",
"description": "============\nSimple Model\n============\n\n.. image:: https://badge.fury.io/py/pysimplemodel.svg\n :target: https://pypi.org/project/pysimplemodel/\n\n.. image:: https://img.shields.io/badge/python-3.6,3.7-blue.svg\n :target: https://github.com/lamenezes/simple-model\n\n.. image:: https://img.shields.io/github/license/lamenezes/simple-model.svg\n :target: https://github.com/lamenezes/simple-model/blob/master/LICENSE\n\n.. image:: https://circleci.com/gh/lamenezes/simple-model.svg?style=shield\n :target: https://circleci.com/gh/lamenezes/simple-model\n\n.. image:: https://codecov.io/gh/lamenezes/simple-model/branch/master/graph/badge.svg\n :target: https://codecov.io/gh/lamenezes/simple-model\n\n\n*SimpleModel* offers a simple way to handle data using classes instead of a\nplenty of lists and dicts.\n\nIt has simple objectives:\n\n- Define models and its fields easily using class attributes, type annotations or tuples (whatever suits your needs)\n- Support for field validation, cleaning and type conversion\n- Easy model conversion to dict\n\n\nQuickstart\n==========\n\nInstalling\n----------\n\nOpen your favorite shell and run the following command:\n\n.. code:: shell\n\n pip install pysimplemodel\n\n\nExample\n-------\n\nDefine your models using type annotations:\n\n.. code:: python\n\n from simple_model import Model\n\n\n class Person(Model):\n age: int\n height: float\n is_active: bool = True\n name: str\n\n\nSimple model automatically creates an initializer for your model and you all set\nto create instances:\n\n.. code:: python\n\n >> person = Person(age=18, height=1.67, name='John Doe')\n >> person.name\n 'John Doe'\n\nAs you have noticed we haven't informed a value for field `is_active`, but the model\nwas still created. That's because we've set a default value of `True` for it and\nthe model takes care of assigning it automatically to the field:\n\n.. code:: python\n\n >> person.is_active\n True\n\n\nSimple model also offers model validation. Empty fields are considered invalid and will\nraise errors upon validation. Let's perform some tests using the previous `Person` model:\n\n.. code:: python\n\n >> person = Person()\n >> print(person.name)\n None\n >> person.validate()\n Traceback (most recent call last):\n ...\n EmptyField: 'height' field cannot be empty\n\nLet's say we want the height and age fields to be optional, that can be achieved with\nthe following piece of code:\n\n.. code:: python\n\n from simple_model import Model\n\n\n class Person(Model):\n age: int = None\n height: float = None\n is_active: bool = True\n name: str\n\n\nNow let's test it:\n\n.. code:: python\n\n >> person = Person(name='Jane Doe', is_active=False)\n >> person.is_active\n False\n >> person.validate()\n True\n\nThe last line won't raise an exception which means the model instance is valid!\nIn case you need the validation to return True or False instead of raising an\nexception that's possible by doing the following:\n\n.. code:: python\n\n >> person.validate(raise_exception=False)\n True\n\n\nYou can also add custom validations by writing class methods prefixed by `validate`\nfollowed by the attribute name, e.g.\n\n.. code:: python\n\n class Person:\n age: int\n height: float\n name: str\n\n def validate_age(self, age):\n if age < 0 or age > 150:\n raise ValidationError('Invalid value for age {!r}'.format(age))\n \n return age\n\n def validate_height(self, height):\n if height <= 0:\n raise ValidationError('Invalid value for height {!r}'.format(age))\n \n return height\n\n\nLet's test it:\n\n.. code:: python\n\n >> person = Person(name='John Doe', age=190)\n >> person.validate()\n Traceback (most recent call last):\n ...\n ValidationError: Invalid value for age 190\n >> other_person = Person(name='Jane Doe', height=-1.67)\n >> other_person.validate()\n Traceback (most recent call last):\n ...\n ValidationError: Invalid value for height -1.67\n\n\nIt is important to note that models don't validate types. Currently types are used\nfor field value conversion.\n\nThe `validate` method also supports cleaning the field values by defining custom transformations\nin the `validate_` methods:\n\n.. code:: python\n\n class Person:\n age: int\n name: str\n\n def validate_name(self, name):\n return name.strip()\n\n >>> person = Person(age=18.0, name='John Doe ')\n >>> person.name\n 'John Doe '\n >> person.age\n 18.0\n >>> person.validate()\n >>> person.name\n 'John Doe'\n >>> person.age # all attributes are converted to its type before cleaning\n 18 # converted from float (18.0) to int (18)\n\n\nFinally, simple model allows you to easily convert your model to dict type using the function `to_dict()`:\n\n.. code:: python\n\n >>> to_dict(person)\n {\n 'age': 18,\n 'name': 'John Doe'\n }\n\n\nDocumentation\n=============\n\nDocs on simple-model.rtfd.io_\n\n.. _simple-model.rtfd.io: https://simple-model.readthedocs.io/en/latest/",
"bugtrack_url": null,
"license": "MIT",
"summary": "Data handling made easy",
"version": "2.4.3",
"project_urls": {
"Homepage": "https://github.com/lamenezes/simple-model"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "d26b5c3f629c95b956b766af81eb61fb54d6bb5d714ef35980e47e06d309080e",
"md5": "f73def7a3d47fa511e32e9267c5c0e06",
"sha256": "03bb62655a9f2eca0e20dea6e5496c482ef7d3503bd16624268ab857cecb0086"
},
"downloads": -1,
"filename": "pysimplemodel-2.4.3.tar.gz",
"has_sig": false,
"md5_digest": "f73def7a3d47fa511e32e9267c5c0e06",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 9963,
"upload_time": "2019-07-04T17:25:46",
"upload_time_iso_8601": "2019-07-04T17:25:46.042455Z",
"url": "https://files.pythonhosted.org/packages/d2/6b/5c3f629c95b956b766af81eb61fb54d6bb5d714ef35980e47e06d309080e/pysimplemodel-2.4.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2019-07-04 17:25:46",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "lamenezes",
"github_project": "simple-model",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"circle": true,
"lcname": "pysimplemodel"
}