[Twisted-Python] Twisted Resources / PathArgs

Clark C. Evans cce at clarkevans.com
Wed Feb 26 22:11:15 EST 2003

On Wed, Feb 26, 2003 at 11:36:33PM +0100, Mario Ruggier wrote:
| Thanks Clark, these little examples and explanations are very helpful.

Oh, glad it helped; I'm a newbie my self.

| Or, to put it differently, how can we make sure that Request acquires 
| the pathargs attribute, so that all children do not have to check for 
| existance?

Ok.  Here is a patched one that violates a bit of encapsulation 
by overriding getChildWithDefault() as well.  Furthermore, this
new version returns pathargs as a list to stay consistent with args.


from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.static import File

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

class DynamicRequest(Resource):
    def isLeaf(self):
        return true
    def render(self, req):
        resp = "uri: %s \nargs: %s\npathargs: %s\n"
        return resp % ( req.uri, req.args, req.pathargs )

def run():
    root = PathArgs()
    root.putChild("dynamic", DynamicRequest())
    site = Site(root)

if '__main__' == __name__:
# And then go to...
# http://localhost:8080/key:one/key:two/another:value/dynamic?key=three

More information about the Twisted-Python mailing list