[Twisted-Python] Twisted Resources / PathArgs

Mario Ruggier mario at ruggier.org
Wed Feb 26 17:36:33 EST 2003

Thanks Clark, these little examples and explanations are very helpful.

I have a question on the PathArgs Resource you propose. Assuming we use
the PathArgs class as you suggest, there will be an exception thrown 
when a
requested "dynamic" URL does not include any actual path args, e.g. the 
http://host/name:value/dynamic/whatever does actually work as 
suggested, with
variable "name" being added to the pathargs dict. However, if we ask 
simply for
http://host/dynamic/whatever then an exception is thrown because we try 
to access
req.pathargs, that is not set in this case (PathArgs.getChild() is not 

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? (To 
me this seems
similar to having a request.args being always defined, even if no args.)

I am re-including your code below, slightly modified, to make myself 



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):
     def __init__(self):
     def getChild(self,path,request):
         if not(hasattr(request,'pathargs')):
             request.pathargs = {}
         pair = path.split(':')
         if 2 == len(pair):
             request.pathargs[pair[0]] = pair[1]
             return self
         return Resource.getChild(self,path,request)

class DynamicRequest(Resource):
     def isLeaf(self):
         return true
     def render(self, req):
         req.content_type = 'text/plain'
         if not(hasattr(req,'pathargs')): # can this check be avoided?
             req.pathargs = {}
         return "uri: %s \npathargs: %s " % ( req.uri, req.pathargs )

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



More information about the Twisted-Python mailing list