我希望根据对象的当前状态有选择地返回一些URL,并且花了很长时间来解决如何在Schema中公开state属性,执行一些逻辑并根据对象状态确定要返回哪些URL:
模型:
class Car(Model):
model = Column(String)
year = Column(String)
running = Column(Boolean) #'0 = not running', '1 = running'和模式:
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>')
})我想要做的是,只有当'running‘属性为0时才返回起始url,当它为1时才返回停止url,但我不清楚如何实现这一点。
棉花糖似乎有一些装饰器,但我如何利用它们的flask-棉花糖?
发布于 2016-12-03 03:11:02
您可以使用post_dump后处理来完成此操作:检查运行状态并删除不适当的字段。这将比有条件地生成它们容易得多。
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>')
})
@ma.post_dump
def postprocess(self, data):
if data['running']:
del data['_links']['start']
else:
del data['_links']['stop']https://stackoverflow.com/questions/30631542
复制相似问题