2015-06-03 20 views
2

我正在尋找有選擇地返回一些基於對象的當前狀態的網址,我有一段時間解決如何在架構中公開狀態屬性,做一些邏輯和決定返回基於對象狀態的網址:瓶棉花糖 - 如何有條件地生成HATEOAS URLS

的型號:

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時纔會返回起始網址,而在1時返回停止網址,但我不清楚如何完成此操作。

棉花糖似乎有幾個裝飾,似乎但我將如何利用他們與燒瓶棉花糖?

回答

0

您可以使用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']