【问题标题】:Using view context in model's _post_put_hook在模型的 _post_put_hook 中使用视图上下文
【发布时间】:2016-10-11 16:16:01
【问题描述】:

我在我的一个 NDB 模型上覆盖了 _post_put_hook(),我想根据原始请求发送到的 URL 更改处理结果的方式:

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 和底层数据库模型之间的巨大鸿沟,但尽管如此,这正是我想要实现的目标。

我似乎想不出一个好的、异步安全的方法来实现这一点。我错过了什么?

【问题讨论】:

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


    【解决方案1】:

    如何将模型实例上的“内部”(_) 属性设置为 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
    

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

    【讨论】:

    • 嘿,非常感谢您提供如此详细的回复!正如您在最后一句话中提到的,这在技术上不是异步安全的,例如,如果我在同一个对象上收到两个我想以不同方式处理的请求,对吗?我实际上刚刚实现了另一个解决方案,虽然仍然有点老套,但我认为解决了我的问题(我很快就会写出来)。再次感谢
    【解决方案2】:

    我已经解决了这个问题(我相信)是一种异步安全的方式,如下所示:

    在我想修改 _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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 2019-12-22
      • 2017-09-24
      • 1970-01-01
      相关资源
      最近更新 更多