txwsgi / doc / examples / demo_fdevent.py

# 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

    def doRead(self):

    def doWrite(self):

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
    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()

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

        read, write, exc = m.fdset()
        resume = environ['x-wsgiorg.suspend'](1000)
        if read:
            readable(read[0], resume)
            yield ''
            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

    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)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.