python - 在 Twisted *之前* 开始服务时执行异步代码

标签 python twisted

我开始我的扭曲应用程序:

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/

相关文章:

Python URL 命令导出到 .xlsx 文件

python - 获取根据修改日期排序的文件夹列表

twisted - 在 Twisted 中,processExited 和 processEnded 之间有什么区别?

python - wxReactor问题

python - ModelForm form_valid() 函数的成功/重定向 URL 问题

python - graph-tool - 从 pandas dataframe 中读取边列表

python - 用于多个客户端的扭曲服务器

python - 当某些项目相互依赖时,如何运行异步进程列表?

python - Numpy 数组索引意外行为

Python Twisted——如何控制 Telnet 或 SSH 中的缓冲/非缓冲输入?