[Twisted-web] twisted.web.wsgi usage example

Jean-Paul Calderone exarkun at divmod.com
Tue Dec 9 16:19:10 EST 2008


On Tue, 9 Dec 2008 14:40:13 -0500, Phil Christensen <phil at bubblehouse.org> wrote:
>Just because I've found myself doing this several times, you might  give an 
>example of how to run an existing WSGI application in twisted.
>
>I would suggest Trac, since you can just import 
>trac.web.main.dispatch_request and pass it as your WSGI application  object, 
>plus it's something that I know I often end up using in tandem  with web 
>projects.

This is pretty easy:

    twistd web --wsgi trac.web.main.dispatch_request

>
>-phil
>
>On Dec 9, 2008, at 12:38 AM, Waldemar Osuch wrote:
>>Hi,
>>I'm trying to come up with an example on how to use the spanking new
>>twisted.web.wsgi
>>module.  Here it is.  Any comments?

Just one, I think

>>
>>8 < 
>>--------------------------------------------------------------------------------------------
>>
>>from twisted.internet import reactor
>>from twisted.application import service, internet
>>from twisted.web import server, static, wsgi
>>from twisted.python import threadpool
>>
>>
>>def wsgi_app(environ, start_response):
>>    status = '200 OK'
>>    response_headers = [('Content-type', 'text/plain')]
>>    start_response(status, response_headers)
>>    return ['Hello from twisted.web.wsgi']
>>
>>
>>class WSGIService(service.Service):
>>    def __init__(self, minPoolSize=5, maxPoolSize=20):
>>        self.pool = threadpool.ThreadPool(minPoolSize, maxPoolSize)
>>
>>    def startService(self):
>>        self.pool.start()
>>        service.Service.startService(self)
>>
>>    def stopService(self):
>>        self.pool.stop()
>>        service.Service.stopService(self)
>>

self.pool.stop() will block until all the threads in the pool finish whatever
job they're on.  This is probably okay for now, but if Twisted's WSGI server
ever changes to deliver request body bytes to WSGI applications incrementally
then this could cause a deadlock.  In order to fix this, there needs to be a
way to shut down the threadpool without blocking the reactor.  This would
make a good enhancement request for ThreadPool.  Another approach would be to
stop the HTTP port so that new requests cannot be made and then wait for all
existing requests to finish before trying to stop the pool.

>>
>>application = service.Application('wsgi')
>>
>>root = static.File("www/documents")
>>site = server.Site(root)
>>internet.TCPServer(8080, site).setServiceParent(application)
>>
>>serv = WSGIService()
>>root.putChild('wsgi', wsgi.WSGIResource(reactor, serv.pool, wsgi_app))
>>serv.setServiceParent(application)
>>

Jean-Paul



More information about the Twisted-web mailing list