[Twisted-web] Twisted to proxy php out to apache?

glyph at divmod.com glyph at divmod.com
Wed May 24 17:34:35 CDT 2006



On Wed, 24 May 2006 12:40:45 -0700, David Reid <dreid at dreid.org> wrote:
>Remi Cool wrote:
>>> Ok, I'm with you with that (I need to read more carefully) ... but what
>>> I would like to do, is pass all requests for files ending with .php (and
>>> maybe .js and .ccs) to be forwarded to another server. Forwarding
>>> everything would make the transition from php to nevow a tad more
>>> difficult.  Would this 'selective' proxying be possible?

>Well unless you've specifically got long standing URLs to worry about

David's explanation was correct, but I tend to expect long-standing URLs to continue to work.  With that in mind: Twisted's philosophy in this regard is to provide simple interfaces so that you can write your own "glue" resources criteria as you see fit.  Since I was bored and stuck in a train station while I was reading this message, here's a quick "left/right" switch for resources.  Toooootally untested, not even run.

The way you'd use it in your program is similar to dreid's .tac example:

SegmentSwitch(lambda segments:
              segments[-1].split('.')[-1] in ('php', 'js', 'css'),
              MyCoolNevowApplication(),
              ReverseProxyResource('localhost', 8080, '/'))


And here's the implementation:

from zope.interface import implements

from twisted.web2 import resource, iweb

class SegmentSwitch(resource.Resource):
    """
    I am a resource that switches between two alternative resource hierarchies
    depending on a callable.
    """

    implements(iweb.IResource)

    def __init__(self, switch, left, right):
        """
        Create a switching resource.

        @param switch: A one-argument callable that takes a sequence of
        segments and returns False to divert to the left resource and True to
        divert to the right.

        @param left: An IResource provider to be used when 'switch' returns
        False.

        @param right: An IResource provider to be used when 'switch' returns
        True.
        """

        self.switch = switch
        self.left = left
        self.right = right

    def locateChild(self, request, segments):
        if self.switch(segments):
            res = self.right
        else:
            res = self.left
        return res.locateChild(request, segments)

    def render(self, request):
        return "OOPS"



More information about the Twisted-web mailing list