views:

89

answers:

2

In my Pylons app, some content is located at URLs that look like http://mysite/data/31415. Users can go to that URL directly, or search for "31415" via the search page. My constraints, however, mean that http://mysite/data/000031415 should go to the same page as the above, as should searches for "0000000000031415." Can I strip leading zeroes from that string in Routes itself, or do I need to do that substitution in the controller file? If it's possible to do it in routing.py, I'd rather do it there - but I can't quite figure it out from the documentation that I'm reading.

A: 

I know I am cheating by introducing a different routing library, since I haven't used Routes, but here's how this is done with Werkzeug's routing package. It lets you specify that a given fragment of the path is an integer. You can also implement a more specialized "converter" by inheriting werkzeug.routing.BaseConverter, if you wanted to parse something more interesting (e.g. a UUID).

Perhaps, Routes has a similar mechanism in place for specialized path-fragment-parsing needs.

import unittest
from werkzeug.routing import Map, Rule

class RoutingWithInts(unittest.TestCase):
    m = Map([Rule('/data/<int:record_locator>', endpoint='data_getter')])

    def test_without_leading_zeros(self):
        urls = self.m.bind('localhost')
        endpoint, urlvars = urls.match('/data/31415')
        self.assertEquals({'record_locator': 31415}, urlvars)

    def test_with_leading_zeros(self):
        urls = self.m.bind('localhost')
        endpoint, urlvars = urls.match('/data/000031415')
        self.assertEquals({'record_locator': 31415}, urlvars)

unittest.main()
Pavel Repin
Hmmm. I could try to coerce the routing variable into an int, that might work. Thanks for the suggestion.
Sean M
@Sean M, it would help if you posted your coercion code here so others having similar difficulties with Routes would benefit as well.
Pavel Repin
I haven't gotten it to work yet, and I suspect that this direction may not be productive. :(
Sean M
+1  A: 

You can actually do that via conditional functions, since they let you modify the variables from the URL in place.

Krinn