Twisted Error:调用Request.finish后,在请求上调用Request.write

时间:2013-10-09 12:40:26

标签: python twisted twisted.web

我正在尝试将慢速计算放入线程中,并在调用Request.finish之后收到错误“在请求上调用Request.write。”

我已经查看了答案,并找到完全相同的问题,但解决方案对我不起作用。请指教。

from twisted.web.server import Site, NOT_DONE_YET
from twisted.web.resource import Resource
from twisted.internet import reactor, threads
from twisted.python import log

import sys
import time


def SlowComputation():
    time.sleep(10)
    return "Lang Computation Result"


def FastComputation():
    return "Fast Computation Result"


class PerformComputation(Resource):
    def Success(self, request):
        request.write('Success')
        request.finish()

    def Failure(self, request):
        request.write('Failure')
        request.finish()

    def render_GET(self, request):
        if 'fast' in request.args:
            d = threads.deferToThread(FastComputation)
            d.addCallback(self.Success(request))
            return NOT_DONE_YET
        if 'slow' in request.args:
            d = threads.deferToThread(SlowComputation)
            d.addCallback(self.Success(request))
            return NOT_DONE_YET


log.startLogging(sys.stdout)
root = Resource()
root.putChild("calculate", PerformComputation())
factory = Site(root)
reactor.listenTCP(8880, factory, interface='localhost')
reactor.run()

1 个答案:

答案 0 :(得分:3)

此:

d.addCallback(self.Success(request))

与:

相同
temp = self.Success(request)
d.addCallback(temp)

,鉴于Success的定义与:

相同
request.write('Success')
request.finish()
temp = None
d.addCallback(None)

在调用Request.finish之后,在请求上调用 Request.write时,这可能会失败。因为d.addCallback(None)引发异常而服务器尝试将错误报告为响应。但是,由于已经调用finish,因此无法写入错误。

使用额外参数向Deferred添加回调的正确方法是d.addCallback(self.Success, request)。尽管如此,Deferred 始终的回调会传递Deferred的结果作为第一个参数 - 因此Success的正确签名是:

def Success(self, result, request):
    ...