在模型' s _post_put_hook中使用视图上下文

时间:2016-06-10 16:00:42

标签: python django google-app-engine django-rest-framework

我在我的一个NDB模型上覆盖了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 ,我想根据原始请求的网址更改处理结果的方式:

{{1}}

我知道这有点难看,弥合了API与底层数据库模型之间的巨大鸿沟,但它仍然是我想要实现的目标。

我似乎无法想到实现这一目标的良好,异步安全的方法。我错过了什么?

2 个答案:

答案 0 :(得分: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()

'foo'和'bar'是正常功能。

然后:

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

关于异步安全性,使用内部属性应该没有任何问题(除非同时在其他地方使用相同的实例)。

答案 1 :(得分: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