Skip to main content
 首页 » 编程设计

python之在 Twisted 上使用 WSGI

2025年05月04日1098°冷暖

我可以同时使用 Twisted 和 mod_wsgi 来尝试提高性能吗?

由于我没有启动 reactor.listenTCP(...),我该如何使用 twisted 的异步方法?:

我尝试过的:

> server.wsgi

def application(environ, start_response): 
    status = '200 OK' 
    output = 'Pong!' 
    response_headers = [('Content-type', 'text/plain'), 
                        ('Content-Length', str(len(output)))] 
    start_response(status, response_headers) 
    # How do I call a twisted async method from here?! 
    # like deferToThread(object.send, environ). 
    return [output] 
 
resource = WSGIResource(reactor, reactor.getThreadPool(), application) 

请您参考如下方法:

你不能。

如果您想使用 Twisted 作为您的 WSGI 容器,那么请使用 Twisted。如果您想使用 Apache,请使用 Apache。但是,如果您使用 Apache 作为 WSGI 容器,那么您将无法使用 Twisted 的功能,因为 Twisted 的事件循环与 Apache 执行网络 I/O 的方式不兼容。

您在代码示例中所做的事情毫无意义,因为 WSGIResource 是 Twisted 的 HTTP 服务器和 WSGI 之间的粘合剂;即使您可以通过 mod_wsgi 以某种方式将 Twisted 塞入正在运行的 Apache HTTPD 进程,您也不需要 WSGIResource,因为 apache 将担任该角色。