flask-marshmallow icon indicating copy to clipboard operation
flask-marshmallow copied to clipboard

conditionally return URLs

Open jamesperi opened this issue 10 years ago • 1 comments

I'm looking to selectively return some urls based on the current state of the object and am having a heck of a time solving how to expose the state property in the Schema, do some logic and determine which URLs to return based on the object state:

The Model:

class Car(Model):
    model = Column(String)
    year = Column(String)
    running = Column(Boolean)   #'0 = not running', '1 = running'

and the schema:

class CarSchema(ma.Schema):
    class Meta:
        fields = ('model', 'year', 'running',  '_links')

    _links = ma.Hyperlinks({
        'self': ma.URLFor('car_detail', id='<id>'),
        'start': ma.URLFor('car_start', id='<id>')
        'stop': ma.URLFor('car_start', id='<id>')
    })

What i'd like to do is have the start url only returned when the 'running' property is 0, and the stop url returned when it's 1, but i'm unclear on how to accomplish this.

Marshmallow seems to have a few decorators that would seem to but how would I leverage them with flask-marshmallow?

jamesperi avatar Jun 03 '15 22:06 jamesperi

I was able to satisfy this use case using the @post_dump decorator.

@post_dump(pass_original=True)
def filter_links(self, data, car):
    if car.running:
        del data['_links']['start']
    else:
        del data['_links']['stop']

The pass_original option is only really necessary if the condition requires data that was excluded by the schema. If you can, you may want to avoid it when working with lists due to https://github.com/marshmallow-code/marshmallow/issues/315.

deckar01 avatar Nov 20 '17 02:11 deckar01