扭曲的延迟回调链
阅读文档和一些用例后。问题出现了如何使用回调链。更准确地说,如何在回调之间传输数据
这是代码:
d = defer.Deferred()
d.addCallback(self.min_active_stack)
d.addCallback(self.min_normalization)
d.addCallback(self.insert_db)
d.callback(0)
def min_active_stack(self,d):
...
return self.dbconn.runQuery(sql_query)
def min_normalization(self,min):
...
return min[0][0]+self.x
def insert_db(self,min_norm):
...
return self.dbconn.runQuery(sql_query)
首先,在 min_active_stack 中,我向 db 发出请求。在 min_normalization 中我处理数据。处理后的数据上的 insert_db 我确实对数据库有一个请求。
这种情况下,数据是通过链来传输的,很简单。 但是,如果在链的中间需要运行比回调更多的内容怎么办?
d = defer.Deferred()
d.addCallback(self.min_active_stack)
d.addCallback(self.stack_shift)
d.addCallback(self.min_normalization)
d.addCallback(self.insert_db)
d.callback(0)
def stack_shift(self, d):
return self.dbconn.runQuery(query)
stack_shift 中不使用任何外部数据,但它应该在 min_active_stack 之后和 insert_db 之前运行。事实证明,min_normalization 来自延迟的 stack_shift 而不是 min_active_stack。
对于我自己来说,我通过在 stack_shiftt: 中添加一行来解决这个问题:
self.temp=d
并在 min_normalization 中使用 self.temp 。
但至于正确的决定呢?
After reading the documentation and a few use cases. The question arose how to use a chain of Callbacks. More precisely how to transfer data between Callbacks
Here is the code:
d = defer.Deferred()
d.addCallback(self.min_active_stack)
d.addCallback(self.min_normalization)
d.addCallback(self.insert_db)
d.callback(0)
def min_active_stack(self,d):
...
return self.dbconn.runQuery(sql_query)
def min_normalization(self,min):
...
return min[0][0]+self.x
def insert_db(self,min_norm):
...
return self.dbconn.runQuery(sql_query)
First, in min_active_stack I do request to db. In min_normalization I process the data. And insert_db on the processed data I do have one request to the db.
In this case, data is transmitted through the chain and it's simple.
But what if in the middle of the chain need to run more then a Callback.
d = defer.Deferred()
d.addCallback(self.min_active_stack)
d.addCallback(self.stack_shift)
d.addCallback(self.min_normalization)
d.addCallback(self.insert_db)
d.callback(0)
def stack_shift(self, d):
return self.dbconn.runQuery(query)
In stack_shift are not used any external data, but it should be run after min_active_stack and before insert_db. It turns out that in min_normalization comes from deferred stack_shift instead of min_active_stack.
For myself, I solved this problem by adding a line in stack_shiftt:
self.temp=d
And use self.temp in min_normalization.
But as far as the right decision?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我其实不明白这个问题。为什么不能将 min_active_stack() 的结果通过 stack_shift() 传递到 min_normalization() 中?
或者因为看起来您想在 stack_shift 中执行异步操作,所以 Deferred 等效项:
I actually don't understand the problem. Why you can't just pass result from min_active_stack() through stack_shift() into min_normalization()?
Or since it looks like you want to do something asynchronous in stack_shift, the Deferred equivalent: