[Twisted-Python] Twisted Resources / PathArgs

Clark C. Evans cce at clarkevans.com
Wed Feb 26 22:43:18 EST 2003


#
# pathargs.py
#
# Author: Clark Evans, Axista, Inc.
# Copyright: public domain
# Date: Wed, Febuary 26, 2003
#
# To test, simply run on the command line and then visit this url:
# http://localhost:8080/key:one/key:two,three/another:value/dynamic?key=four
#

from twisted.web.resource import Resource
class PathArgs(Resource):
    """ Provides a mechanism to add 'pathargs' attribute to
        each request, and to populate it with instances of
        key:value pairs found in child paths.  The value for
        each key will be an array, optionally split further
        with a comma.
    """
    def __init__(self,splitOnComma=0):
        Resource.__init__(self)
        self.splitOnComma = splitOnComma
    def getChild(self,path,request):
        pair = path.split(':')
        if 2 == len(pair):
            (key,val) = pair
            lst = request.pathargs.get(key,[])
            if not lst: request.pathargs[key] = lst
            if self.splitOnComma:
                for itm in val.split(','):
                    lst.append(itm)
            else:
                lst.append(val)
            return self
        return Resource.getChild(self,path,request)
    def getChildWithDefault(self,path,request):
        if not(hasattr(request,'pathargs')):
            request.pathargs = {}
        return Resource.getChildWithDefault(self,path,request)

def test():
    from twisted.internet import reactor
    from twisted.web.server import Site
    from twisted.web.static import File

    class DynamicRequest(Resource):
        def isLeaf(self):
            return true
        def render(self, req):
            req.setHeader('Content-type','text/plain')
            resp = 'uri: %s \nargs: %s\npathargs: %s\n'
            return resp % ( req.uri, req.args, req.pathargs )

    root = PathArgs(splitOnComma=1)
    root.putChild('dynamic', DynamicRequest())
    root.putChild('static',File('.'))
    site = Site(root)
    reactor.listenTCP(8080,site)
    reactor.run()

if '__main__' == __name__:
    test()




More information about the Twisted-Python mailing list