我有一个服务器,我在其中实现了 NetstringReceiver 协议的一个子协议。我希望它根据客户端的请求执行异步操作(使用 txredisapi),然后以操作结果进行响应。我的代码的概括:
class MyProtocol(NetstringReceiver):
def stringReceived(self, request):
d = async_function_that_returns_deferred(request)
d.addCallback(self.respond)
# self.sendString(myString)
def respond(self, result_of_async_function):
self.sendString(result_of_async_function)
在上面的代码中,连接到我的服务器的客户端没有得到响应。但是,如果我取消注释,它确实会得到 myString
# self.sendString(myString)
我也知道 result_of_async_function 是一个非空字符串,因为我将它打印到 stdout 。
我该怎么做才能让我用异步函数的结果响应客户端?
更新:可运行的源代码
from twisted.internet import reactor, defer, protocol
from twisted.protocols.basic import NetstringReceiver
from twisted.internet.task import deferLater
def f():
return "RESPONSE"
class MyProtocol(NetstringReceiver):
def stringReceived(self, _):
d = deferLater(reactor, 5, f)
d.addCallback(self.reply)
# self.sendString(str(f())) # Note that this DOES send the string.
def reply(self, response):
self.sendString(str(response)) # Why does this not send the string and how to fix?
class MyFactory(protocol.ServerFactory):
protocol = MyProtocol
def main():
factory = MyFactory()
from twisted.internet import reactor
port = reactor.listenTCP(8888, factory, )
print 'Serving on %s' % port.getHost()
reactor.run()
if __name__ == "__main__":
main()