Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support factories and serializers in schema directly #60

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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