python - 调用 Request.finish 后在请求上调用 Twisted 错误 : Request. write

标签 python twisted twisted.web

我试图将缓慢的计算放入线程内,并收到错误“Request.write 在调用 Request.finish 后对请求进行了调用。”

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

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()

最佳答案

这个:

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):
    ...

关于python - 调用 Request.finish 后在请求上调用 Twisted 错误 : Request. write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19272307/

相关文章:

python - python 中的运算符@?是什么?

python - 如何通过 http 代理传递所有 Python 的流量?

python - Twisted/Starpy FastAgi 应用只能正确处理一个调用

python - 扭曲的http客户端

ssl - 扭曲的 listenSSL 虚拟主机

python - 如何将 pycurl 与 Twisted Python 结合使用?

python - Matplotlib 步进图旋转

python - 在 pyomo 中如何从目标函数中提取二阶导数

python - 无法在 Twisted Web 服务器上运行 Flask,WSGI 应用程序错误

python - 如何解决websocket ping超时?