Pyramid: query string extension for each URL constructed by route_url

I use a pyramid of web graphics and submitting URLs where I have defined many routes, e.g.

config.add_route('login', '/login') config.add_route('logout', '/logout') 

Now I want to add something to the query string, so that the URLs that are created

 request.route_url('login') 

actually

 /login?foo=bar 

This should be done on a project basis to avoid writing

 request.route_url('login', _query={'foo': 'bar'}) 

every time I want to create a url.

What place do you need to do? Should I somehow inherit the pyramid.request class and overwrite the route_url method? Is there an event or hook that I can use?

+4
source share
2 answers

You can identify the regenerator and assign it to your routes.

 def add_query_pregen(request, elements, kwargs): query = kwargs.setdefault('_query', {}) query.setdefault('foo', 'bar') return elements, kwargs def add_route_with_query(*args, **kwargs): kwargs['pregenerator'] = add_query_pregen config.add_route(*args, **kwargs) add_route_with_query('login', '/login') add_route_with_query('logout', '/logout') 

Basically, a pregenerator is called anytime you call request.route_url and the like, and elements and kwargs are passed, allowing you to mutate them before the URL is actually generated.

+3
source

Based on the discussion on this site, I implemented the following solution:

 from pyramid.request import Request as OldRequest class Request(OldRequest): def route_url(self, route_name, *elements, **kw): qs = kw.get('_query', {}) if 'hid' in qs: raise Exception('hid exists in query string') qs['hid'] = 1337 kw['_query'] = qs return self.route_without_hid(route_name, *elements, **kw) def route_url_without_hid(self, route_name, *elements, **kw): return super(Request, self).route_url(route_name, *elements, **kw) 

and also leaves it possible to create URLs that do not have hidden objects.

0
source

All Articles