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