duffn duffn - 1 year ago 107
Python Question

Flask-Restless Marshmallow serializer

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


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)


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)


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?

Answer Source

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] } )