Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

conditionally return URLs #22

Open
jamesperi opened this issue Jun 3, 2015 · 1 comment
Open

conditionally return URLs #22

jamesperi opened this issue Jun 3, 2015 · 1 comment

Comments

@jamesperi
Copy link

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?

@deckar01
Copy link
Member

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 marshmallow-code/marshmallow#315.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants