Source

txwsgi / doc / examples / demo_fdevent.py

#!/usr/bin/python
# Copyright (c) 2008 Christopher Stawarz
# Copyright (c) 2010 Manlio Perillo (manlio.perillo@gmail.com).
# See LICENSE for details.

from StringIO import StringIO

import pycurl

from twisted.python import log
from twisted.internet import reactor
from twisted.application import service, strports
from twisted.web import server

from txwsgi import WSGIResource


# Helper functions
class FileDescriptor(object):
    def __init__(self, fd, resume):
        self.fd = fd
        self.resume = resume

    def logPrefix(self):
        return 'event'

    def fileno(self):
        return self.fd

    def connectionLost(self, reason):
        # XXX check me
        log.err(reason)

    def doRead(self):
        reactor.removeReader(self)
        self.resume()

    def doWrite(self):
        reactor.removeWriter(self)
        self.resume()

def readable(fd, resume):
    reactor.addReader(FileDescriptor(fd, resume))

def writeable(fd, resume):
    reactor.addWriter(FileDescriptor(fd, resume))


def pyorg_proxy(environ, start_response):
    """A WSGI application that show how the example specified in the
    U{fdevent<http://www.wsgi.org/wsgi/Specifications/fdevent/>
    extension can be written using I{x-wsgiorg.suspend},
    I{x-wsgiorg.suspend_status} and the Twisted reactor API.
    """

    result = StringIO()

    c = pycurl.Curl()
    c.setopt(pycurl.URL, 'http://python.org' + environ['PATH_INFO'])
    c.setopt(pycurl.WRITEFUNCTION, result.write)

    m = pycurl.CurlMulti()
    m.add_handle(c)

    while True:
        while True:
            ret, num_handles = m.perform()
            if ret != pycurl.E_CALL_MULTI_PERFORM:
                break
        if not num_handles:
            break

        read, write, exc = m.fdset()
        resume = environ['x-wsgiorg.suspend'](1000)
        if read:
            readable(read[0], resume)
            yield ''
        else:
            writeable(write[0], resume)
            yield ''

        if environ['x-wsgiorg.suspend_status']() == -1:
            msg = 'The request to python.org timed out.'
            start_response('504 Gateway Timeout',
                           [('Content-Type', 'text/plain'),
                            ('Content-Length', str(len(msg)))])
            yield msg
            return

    start_response('200 OK', [('Content-Type', 'application/octet-stream'),
                              ('Content-Length', str(result.len))])
    yield result.getvalue()


res = WSGIResource(reactor, pyorg_proxy)
site = server.Site(res)
application = service.Application('demo fdevent')

s = strports.service('tcp:8080', site)
s.setServiceParent(application)