如何將模型實例上的'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
關於異步安全,不應該有使用內部屬性(除非同一實例別處使用同時地)的任何問題。
嘿,感謝這麼多這麼詳細的答覆!正如你在最後一句中提到的,如果我在同一個對象上得到兩個要處理不同的對象的請求,這在技術上不是異步安全的?實際上,我剛剛實現了另一個解決方案,儘管它仍然有點冒險,但我認爲解決了我的問題(我很快就會把它寫出來)。再次感謝 – DaveBensonPhillips