Skip to content

Commit

Permalink
Support factories and serializers in schema directly
Browse files Browse the repository at this point in the history
  • Loading branch information
tsx committed May 12, 2021
1 parent ccfd107 commit 1e83efb
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions cleancat/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,12 @@ def clean(self, value):
)


class SchemaOptions:
def __init__(self, factory=None, serializer=None):
self.factory = factory
self.serializer = serializer


class Schema(object):
"""
Base Schema class. Provides core behavior like fields declaration
Expand Down Expand Up @@ -745,6 +751,10 @@ def get_fields(cls):
fields[field_name] = field
return fields

@classmethod
def _get_options(cls):
return getattr(cls, '__options__', SchemaOptions())

@classmethod
def obj_to_dict(cls, obj):
"""
Expand Down Expand Up @@ -851,7 +861,10 @@ def full_clean(self):
self.errors = [e.args and e.args[0]]

self.raise_on_errors()
return self.data
factory = self._get_options().factory
if factory is None:
return self.data
return factory(**self.data)

def raise_on_errors(self):
if self.field_errors or self.errors:
Expand All @@ -877,9 +890,14 @@ def external_clean(self, cls, raise_on_errors=True):

def serialize(self):
data = {}
serializer = self._get_options().serializer
if serializer is None:
original_data = self.data
else:
original_data = serializer(self.data)
for field_name, field in self.fields.items():
raw_field_name = field.raw_field_name or field_name
value = self.data[field_name]
value = original_data[field_name]
data[raw_field_name] = field.serialize(value)
return data

Expand Down

0 comments on commit 1e83efb

Please sign in to comment.