扭曲deferToThread中延迟的未处理错误

时间:2018-03-13 19:52:44

标签: python twisted twisted.web twisted.internet

我有来自twisted的客户端/服务器代码示例。现在,我的要求是当从客户端调用服务器时 - 服务器将调用推迟到一个线程,该线程实际上回复客户端,服务器可以执行其他操作。简单来说,假设客户端C1使用模板Temp1调用服务器S1。服务器将其推迟到线程T1。 T1现在必须处理功能A,B和C,最后返回客户端C1。下面是我的服务器代码。

我是新来的扭曲,我收到错误:Deferred中的未处理错误:

from twisted.internet import reactor, protocol, threads

def foo():
    time.sleep(5)
    print('Hello how are you!!!!')

def print_result():
    print('Processing done!!')

def onError():
    print('Error!!!!')

class Echo(protocol.Protocol):
    """This is just about the simplest possible protocol"""
    def process_func(self, data):
        print('hello i am in process_func!!!')
        self.transport.write(data)
        return foo()

    def onErrorfunc(self):
        onError()

    def onProcessDone(self):
        print_result()

    def dataReceived(self, data):
        "As soon as any data is received, write it back."
        # thr = threading.Thread(target=foo, args=(), kwargs={})
        # thr.start()
        d = threads.deferToThread(self.process_func, *data)
        d.addCallback(self.onProcessDone)
        d.addErrback(self.onErrorfunc)
        # do something else here
        # self.transport.write(data)

def main():
    """This runs the protocol on port 8000"""
    factory = protocol.ServerFactory()
    factory.protocol = Echo
    reactor.listenTCP(8000,factory)
    reactor.run()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()

为什么要扭曲,因为客户端/服务器已经被扭曲编写,我正在进行微小的更改。感谢帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

很难说出你的Unhandled error in Deferred源于你的例子,因为你的例子被语法错误所覆盖,但我会尝试使用我的直觉并重写你想要做的事情:)。我已经发表了一些评论,因此请查看您的代码和此代码的不同之处。

import time
from twisted.internet import reactor, protocol, threads

def foo():
    # this function didn't return anything in your example
    # now it returns a string
    time.sleep(5)
    return 'Hello how are you!!!!'

class Echo(protocol.Protocol):
    def process_func(self, data):
        # data is unused here, typically you would "do something" to data in a thread
        # remember data is a bytes type not string!
        print('hello i am in process_func!!!')
        return foo()

    def onErrorfunc(self, failure):
        print('Error: {0}'.format(failure.value))

    def onProcessDone(self, result):
        # result is the string returned from process_func()
        # if Python version >= 3 then transport.write arg must be bytes
        self.transport.write(result.encode('utf8'))
        print('Processing done!!')

    def dataReceived(self, data):
        d = threads.deferToThread(self.process_func, data)
        d.addCallback(self.onProcessDone)
        d.addErrback(self.onErrorfunc)

请勿在线程中使用self.transport.write(),因为它使用Twisted reactor进行了预定。而是在线程中的计算完成后在回调中运行它。线程只应用于密集计算,因为Twisted为您提供了大量选项,可以在单个线程中有效地运行代码。