Question

I need to pass a subpath as a param in a route generated by Pyramid. I tried using urllib.encode and urllib.quote but get a "resource could not be found error" either way.

route generation:

mypath='a/b/c'
new_route = route_url('new_model_route', self.request, subpath=urllib.encode(mypath))

my route:

config.add_route('new_model_route', '/model/new/{subpath}')

generated url (with "resource not found error")

http://127.0.0.1:6544/rnd2/model/new/a%2Fb%2Fc

I know it has to do with the escaping because the url http://blah/model/new/a works.

Was it helpful?

Solution

The route pattern /model/new/{subpath} would never match /model/new/a/b/c so I don't understand why you would be able to generate a URL for that pattern?

It is possible to pass the rest of the url as elements, however.

config.add_route('new_model_route', '/model/new/{subpath}')
request.route_url('new_model_route', 'b', 'c', subpath='a')
# /model/new/a/b/c

On the other hand, you have another option. You can create a new route to match these urls, such as:

config.add_route('new_model_route', '/model/new/*subpath')
# matches /model/new/a, /model/new/a/b, etc

request.route_url('new_model_route', subpath=('a', 'b', 'c'))
# /model/new/a/b/c

If you didn't actually want to match these URLs for some reason, you can add static=True to the add_route call, which means that you are only using the route name to generate urls but not to match them on incoming requests.

subpath and traverse happen to be special (this is all documented) but if you were hellbent on using 'a/b/c' you could use something else in the route pattern:

config.add_route('new_model_route', '/model/new/*rest')
# matches /model/new/a, /model/new/a/b, etc

request.route_url('new_model_route', rest='a/b/c')
# /model/new/a/b/c

Oh and since I'm on a roll, you can use the original approach with a simpler url which you may already have in your system.

config.add_route('new_model_route', '/model/new')
# matches /model/new only

request.route_url('new_model_route', 'a', 'b', 'c')
# /model/new/a/b/c
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top