Skip to content

Commit

Permalink
Add docs to README.rst about pavlova parsers
Browse files Browse the repository at this point in the history
  • Loading branch information
solarnz committed Sep 5, 2018
1 parent f8e9ac9 commit 6a19d20
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,57 @@ Usage with Flask
app.run()
Adding Custom Types
###################

There are a couple of different ways to implement new types for parsing in
pavlova. In general, the process is to add a parser a specific type. For
validation you should raise a TypeError or ValueError.

The first one, is creating a new type that extends an existing base type. Here
is an example on how to implement an Email type, which is a string but performs
validation.

.. code-block:: python
from pavlova import Pavlova
from pavlova.parsers import GenericParser
class Email(str):
def __new__(cls, input_value: typing.Any) -> str:
if isinstance(input_value, str):
if '@' in input_value:
return str(input_value)
raise ValueError()
raise TypeError()
pavlova = Pavlova()
pavlova.register_parser(Email, GenericParser(pavlova, Email))
Another way, is to implement your own pavlova parser, rather than using your
the built in `GenericParser` parser.

.. code-block:: python
import datetime
from typing import Any, Tuple
import dateparser
from pavlova import Pavlova
from pavlova.parsers import PavlovaParser
class DatetimeParser(PavlovaParser[datetime.datetime]):
"Parses a datetime"
def parse_input(self,
input_value: Any,
field_type: Type,
path: Tuple[str, ...]) -> datetime.datetime:
return dateparser.parse(input_value)
pavlova = Pavlova()
pavlova.register_parser(datetime.DateTime, DatetimeParser(pavlova))
Requirements
############

Expand Down

0 comments on commit 6a19d20

Please sign in to comment.