Flask-Restless Marshmallow serializer

1.3k views Asked by At

I'm trying to exclude columns in a Flask-Restless API using a custom deserializer with Marshmallow as suggested by the docs:

serializers.py

class HeatSchema(Schema):
    id = fields.Integer()
    heat_index = fields.Integer()
    updated_at = fields.DateTime()

class Meta:
    exclude = ('updated_at',)

def make_object(self, data):
    print 'Making object from', data
    return Heat(**data)

server.py

from serializers import HeatSchema

heat_schema = HeatSchema()

def heat_serializer(instance):
    return heat_schema.dump(instance).data

def heat_deserializer(data):
    return heat_schema.load(data).data

apimanager = APIManager(app, flask_sqlalchemy_db=db)

apimanager.create_api(
    heat,
    methods=['GET'],
    url_prefix='/api/v1',
    collection_name='heat',
    results_per_page=10,
    serializer=heat_serializer,
    deserializer=heat_deserializer
)

I get the same response from the API regardless of what I do with the Heat schema. I can put

blahblah = fields.Integer()

without any change. I can't even hit a breakpoint in the serializer while debugging so I assume I have this setup incorrectly with Flask-Restless?

2

There are 2 answers

1
sickrandir On BEST ANSWER

I also experienced the same problem. It seems that the behaviour appears only for GET_MANY functions. If you try to GET a single object instance it should be compliant with the marshmallow schema. This is a strange behaviour that's been reported here on the Flask-restless bug tracker: https://github.com/jfinkels/flask-restless/issues/167

There the user itsrifat offered the workaround to add a postprocessor:


person_schema = PersonSchema()

def person_deserializer(data): return person_schema.load(data).data

def person_after_get_many(result=None, search_params=None, **kw): result['objects'] = [person_deserializer(obj) for obj in result['objects']]

apimanager.create_api(Person,methods=['GET', 'POST','PUT', 'DELETE'], postprocessors={ 'GET_MANY':[person_after_get_many] } )

0
ISONecroMAn On

The Meta class supposed to be inside Schema class.

Meta: is where the configuration is added to the schema class.

 class HeatSchema(Schema):
     id = fields.Integer()
     heat_index = fields.Integer()
     updated_at = fields.DateTime()

     class Meta:
         exclude = ('updated_at',)

     def make_object(self, data):
         print 'Making object from', data
         return Heat(**data)