我开始我的扭曲应用程序:
application = twisted.application.service.Application('myserv')
my_service = MyService()
my_service.setServiceParent(application)
my_factory = twisted.internet.protocol.ServerFactory()
my_factory.protocol = MyProtocol
twisted.application.internet.TCPServer(port, my_factory).setServiceParent(application)
class MyService:
def startService(self):
#only synchronous code here?
在此服务可以接受客户端 tcp 连接之前,我需要建立到 redis 服务器的连接,这涉及执行异步代码。我想将 d=txredisapi.Connection()
或 d = yield txredisapi.Connection()
与 inlineCallbacks
一起使用。这个延迟必须在服务启动之前触发(在客户端的 tcp 连接被接受之前)。启动 txredisapi.Connection()
的最佳位置是什么?理想情况下,我想将它放在 MyService
类中。
最佳答案
只需在顶层编写创建 Redis 连接并将其传递给 MyService 的函数。 可以在异步代码中添加服务。
application = twisted.application.service.Application("myserv")
@defer.inlineCallbacks
def startApp():
rc = yeld txredisapi.Connection()
my_service = MyService(rc)
my_service.setServiceParent(application)
my_factory = twisted.internet.protocol.ServerFactory()
my_factory.protocol = MyProtocol
twisted.application.internet.TCPServer(port, my_factory).setServiceParent(application)
startApp()
关于python - 在 Twisted *之前* 开始服务时执行异步代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16204544/