我试图将慢速计算放入线程中,并收到错误“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()