3

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?

doru
  • 9,022
  • 2
  • 33
  • 43
duffn
  • 3,690
  • 8
  • 33
  • 68

2 Answers2

3

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

sickrandir
  • 123
  • 10
  • There is also new style serializer classes for one and many objects serialization check here https://flask-restless.readthedocs.io/en/latest/serialization.html . When I checked it, flask-restless was 1.0.0b1 – alexche8 Apr 07 '17 at 12:10
0

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)
ISONecroMAn
  • 1,460
  • 2
  • 16
  • 23