""" run python web.rewrite.example.py and then open a browser to localhost:8080/data/foo/bar The two segments of the path below /data are transformed into query arguments using the rewrite function pathToArgs. The root resource is wrapped with the rewrite resource The second arg to RewriterResource is the rewrite function. The rewrite function can be thought of as a rule + an action: If the request satisfies the rule, the request is rewritten. This rewrite happens before the web framework passes the request object to any resource in root (including root itself). It is possible to give more than one rewrite function; they will all have a chance to rewrite the request object. If you look at pathToArgs, everything below the if statement is the rewrite action. Part of the action is self explanatory: - request.args is added (now the handling resources have access to request.args) - request.path is explicitly set to '/data' The intent of this rewrite implies /data is a leaf resource. And part of it is a little confusing - request.postpath -- this is not as straight forward. When the Request object is first created, the raw HTTP headers of the actual request from your browser are processed. Part of that involves splitting the PATH on '/' and storing that in request.postpath. Then, for every hop down a resource tree, the head element of postpath is popped and appended to prepath. request.path represents the full requested path. """ from twisted.web import resource from twisted.web import rewrite from twisted.web import server from twisted.internet import reactor class GenericResource(resource.Resource): def render(self, request): return "dummy resource page" class DataResource(resource.Resource): def render(self, request): """request.args are where GET request args are stored. (From docs) For example, for a URI with 'foo=bar&foo=baz&quux=spam' for its query part, args will be {'foo': ['bar', 'baz'], 'quux': ['spam']} """ print request.args request.write(str(request.args)) return "" def pathToArgs(request): """assume segments of path following "data" are values for the keys: - sta - orid localhost:8008/data/109C/39495/ -> localhost:8008/data?sta=109C&orid=39495 """ if len(request.postpath) == 3 and request.postpath[0] == 'data': sta = request.postpath[1] orid = request.postpath[2] request.args = {'sta':[sta], 'orid':[orid]} request.postpath = ['data'] request.path = '/data' root = GenericResource() root.putChild('', root) root.putChild('test', GenericResource()) root.putChild('data', DataResource()) rewrite_root = rewrite.RewriterResource(root, pathToArgs) site = server.Site(rewrite_root) reactor.listenTCP(8080, site) reactor.run()