[Cubicweb] Custom URL rewriters

Adrien Di Mascio adrien.dimascio at logilab.fr
Fri Sep 16 13:04:13 CEST 2011

Hi all,

In a recent project, I've been using two custom redirect mechanisms:

- a ``CallbackURLRewriter`` that maps a regexp to a callback
   to be called if the input url matches. In a way, it's only a
   generalization of the ``SimpleReqRewriter`` : instead of having
   a dict of properties that will update the request's form, it simply
   calls a callback with the input url, the request, and the
   regexp's MatchObject.

- a ``GotoUrl`` object (a _really_ bad an counter-intuitive name)
   that re-enters the rewriter process with another input url.

Here is what code looks like with CallbackRewriter::

   class MyRewriter(CallbackURLRewriter):
       rules = [
           (rgx(r'a-regexp-maybe-with-groups'), my_callback),
           # ...

   def my_callback(req, input_url, match_object):

The GotoUrl handling is a bit trickier::

   class MyRewriter(SimpleReqRewriter):
       rules = [
         (rgx('/foo(/(bar|baz).*)'), GotoUrl(r'\1', foo=True)),
         (rgx('/bar(/.*?)'), GotoUrl(r'\1', vid='some-custom-view')),
         (rgx('/baz(/.*?)'), GotoUrl(r'\1', vid='another-custom-view')),
         # ...

In that case, if the input url is ``foo/bar/whatever``:

- the first regexp matches, request's form is updated with
   {'foo': True} and the rewriting process starts again with
   ``/bar/whatever`` ...

- ... which in turn is matched by the second regexp, the request's
   form is updated with {'vid': 'some-custom-view'}, the rewriting
   process starts again with ``/whatever`` and so on.

I think that at least the first rewriter deserves to be in CW. Any opinion ?

Adrien Di Mascio - LOGILAB, Paris (France).
Formations - http://www.logilab.fr/formations
Développements - http://www.logilab.fr/services
Gestion de connaissances - http://www.cubicweb.org/

More information about the Cubicweb mailing list