2016-06-10 15 views
0

我已經在我的NDB的車型之一覆蓋_post_put_hook()使用視圖方面,我想改變原來的請求是由我處理我的結果取決於URL的方式:模型的_post_put_hook

def _post_put_hook(self, future): 
    key = future.get_result() 
    # Do some processing 
    if <model was made thanks to POST call to /foo>: 
     # Do one thing 
    else: 
     # Do another 

我知道這有點醜陋,彌合了API和底層數據庫模型之間的巨大鴻溝,但這正是我想要實現的。

我似乎無法想到一個好的,異步安全的方式來實現這一點。我錯過了什麼?

回答

0

我在(我相信)解決,這是一個異步安全的方式如下:

在我想要的看法已經修改_post_put_hook()行爲,在未來實例:

def some_processor(self): 
    ... 
    future = foo.put_async() 
    future.my_flag = True # Add custom flag here 
    return future 

然後在我_post_put_hook()

def _post_put_hook(self, future): 
    key = future.get_result() 
    if getattr(future, 'my_flag', False): 
     # Do one thing 
    else: 
     # Do another 
1

如何將模型實例上的'internal'(_)屬性設置爲post鉤子使用的標誌,字符串或函數?持久化數據時,NDB將忽略屬性字段。

如:

class TestModel(ndb.Model): 
     xyz = ndb.StringProperty() 
     ... 

     def _post_put_hook(self, future): 
      key = future.get_result() 
      # Do some processing 
      try: 
       fooFlag = self._fooFlag 
      except: 
       fooFlag = False # default if _fooFlag is not set 
      if fooFlag: 
       # Do one thing 
      else: 
       # Do another 

如:

test = TestModel(xyz='abc', ...) 
    test._fooFlag = ... #do your foo URL test here 
    test.put() 

你也可以使用一個函數,而不是如

test = TestModel(xyz='abc', ...) 
    test._postFunc = foo if 'foo' in url else 'bar' # etc 
    test.put() 

如果 '富' 和 '酒吧' 是正常的功能。

然後:

def _post_put_hook(self, future): 
     ... 
     try: 
      func = self._postFunc 
     except: 
      func = None # no _postFunc set 
     if func is not None: 
      func(self) # handle exceptions as desired 

關於異步安全,不應該有使用內部屬性(除非同一實例別處使用同時地)的任何問題。

+0

嘿,感謝這麼多這麼詳細的答覆!正如你在最後一句中提到的,如果我在同一個對象上得到兩個要處理不同的對象的請求,這在技術上不是異步安全的?實際上,我剛剛實現了另一個解決方案,儘管它仍然有點冒險,但我認爲解決了我的問題(我很快就會把它寫出來)。再次感謝 – DaveBensonPhillips