-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserializer.py
More file actions
39 lines (28 loc) · 1.38 KB
/
serializer.py
File metadata and controls
39 lines (28 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from marshmallow_sqlalchemy import ModelConversionError, ModelSchema
from sqlalchemy import event
from sqlalchemy.orm import mapper
class CustomModelSchema(ModelSchema):
''' Class to help link Model and Schema '''
def __init_subclass__(cls):
cls.Meta.model.__marshmallow__ = cls
def setup_serializer(base):
''' Create a function that injects (de)serializer classes and methods '''
def setup_schema_fn(base):
for class_ in base._decl_class_registry.values():
if hasattr(class_, '__tablename__'):
# If Model already has a schema do not override it
if not hasattr(class_, '__marshmallow__'):
class Meta():
model = class_
sqla_session = class_.session
strict = True
include_fk = True
schema_class_name = '%sSchema' % class_.__name__
schema_class = type(schema_class_name,
(ModelSchema,),
{'Meta': Meta})
setattr(class_, '__marshmallow__', schema_class)
# Listen for the SQLAlchemy event and run setup_schema.
# Note: This has to be done after Base and session are setup
event.listen(mapper, 'after_configured', setup_schema_fn(base))
return setup_schema_fn