Is there a way to do reverse url resolve in twisted?

126 views Asked by At

In pretty much similar way django can resolve (view_name, args, kwargs) into a string url I'd like to do the same with Resources in twisted.

So I would do urlresolve(Resource, args) and it would return a string url I could use in templates or redirects etc.

I'm thiking simply attaching the url to the Resource classes itself and giving it urlresolve method to handle the dynamic arguments. I know this duplicates the url information but it would be good enough for me right now. I think it should actually be pretty simple to support this properly but I'd expect there already exists something, I was just unable to find it.

2

There are 2 answers

0
Max On

You are right, I don't think that you can do this with Twisted. The reason is that a Resource only knows about its subresources, not it's place in the hierarchy. I.e.

rootResource = Resource(...)
barResource = Resource(...)
fooResource = Resource(...)

rootResource.putChild('foo', fooResource)
fooResource.putChild('bar', barResource)

# barResource doesn't know it's under foo/bar

I think your idea about attaching a url field to a Resource is good. Then you can do something of the sort:

import urllib
args = dict(alpha= 1,beta=2)
resolvedUrl = '{0}?{1}'.format(resource.url, urllib.urlencode(args))
1
Glyph On

The problem with this question is that a Resource might be present at one, zero, or many URLs. If you want to have your own resource type which is available only at one URL, then it can have its own method for identifying which one it's present at.