Using WSGI on Twisted
-
30-04-2021 - |
Question
Can I use Twisted and mod_wsgi together, to try some gain in performance?
Since I am not starting a reactor.listenTCP(...), how do I use the async methods of twisted?:
What I have tried:
> 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)
Solution
You can't.
If you want to use Twisted as your WSGI container, then use Twisted. If you want to use Apache, then use Apache. However, if you use Apache as your WSGI container, then you will not be able to use features from Twisted, because Twisted's event loop is not compatible with the way Apache does network I/O.
What you're doing in the code example is doubly meaningless, as WSGIResource
is the glue between Twisted's HTTP server and WSGI; even if you could somehow jam Twisted into a running Apache HTTPD process via mod_wsgi
, you would not need a WSGIResource
, since apache would be filling that role.