2

有人可以解释以下之间的区别。我真的很难掌握 Deferred 的概念,我以为我已经掌握了它,因为我整天都在做例子。但我想我一定是代码盲。我敢肯定它真的很简单。

这行得通。

from twisted.spread import pb
from twisted.internet import reactor
from twisted.python import util


if __name__ == '__main__':

    def print_result(result):
        print result

    def add_numbers(obj, a, b):
        obj.callRemote("add_numbers", a, b)



    factory = pb.PBClientFactory()
    reactor.connectTCP("localhost", 8789, factory)
    d = factory.getRootObject()
    d.addCallback(lambda object: object.callRemote("add_numbers", 1, 2))
    d.addErrback(lambda reason: 'error: '+str(reason.value))
    d.addCallback(print_result)
    d.addErrback(lambda reason: 'error: '+str(reason.value))
    d.addCallback(lambda _: reactor.stop())
    d = factory.getRootObject()

    reactor.run()

而这并没有

from twisted.spread import pb
from twisted.internet import reactor
from twisted.python import util


if __name__ == '__main__':

    def print_result(result):
        print result

    def add_numbers(obj, a, b):
        obj.callRemote("add_numbers", a, b)



    factory = pb.PBClientFactory()
    reactor.connectTCP("localhost", 8789, factory)
    d = factory.getRootObject()
    d.addCallback(add_numbers, 1, 2)
    d.addErrback(lambda reason: 'error: '+str(reason.value))
    d.addCallback(print_result)
    d.addErrback(lambda reason: 'error: '+str(reason.value))
    d.addCallback(lambda _: reactor.stop())
    d = factory.getRootObject()

    reactor.run()

我一生都无法弄清楚为什么它会因以下错误而崩溃:

Unhandled error in Deferred:
Unhandled Error
Traceback (most recent call last):
Failure: twisted.spread.pb.PBConnectionLost: [Failure instance: Traceback (failure  with no frames): <class 'twisted.internet.error.ConnectionLost'>: Connection to the other side was lost in a non-clean fashion: Connection lost.
]

服务器端代码是

from twisted.spread import pb
from twisted.internet import reactor

class Echoer(pb.Root):
    def remote_echo(self, st):
        print 'echoing:', st
        return st

    def remote_add_numbers(self, a, b):
        print 'adding:', a, b
        c = a + b
        return c

if __name__ == '__main__':
    reactor.listenTCP(8789, pb.PBServerFactory(Echoer()))
    reactor.run()
4

1 回答 1

2

您的工作示例和损坏示例之间的区别在于lambda表达式隐式返回其结果。它的结果是 a Deferred,这意味着链中的下一个回调将等待执行,直到它的结果可用。

如果您更改 的定义add_numbers以返回 的结果callRemote,如下所示:

def add_numbers(obj, a, b):
    return obj.callRemote("add_numbers", a, b)

然后你破碎的例子将再次开始工作。

于 2013-11-30T12:09:09.480 回答