开发者

Rewriting An URL With Regular Expression Substitution in Routes

开发者 https://www.devze.com 2022-12-23 01:16 出处:网络
In my Pylons app, some content is located at URLs that look like http://mysite/data/31415.Users can go to that URL direct开发者_Go百科ly, or search for \"31415\" via the search page.My constraints, ho

In my Pylons app, some content is located at URLs that look like http://mysite/data/31415. Users can go to that URL direct开发者_Go百科ly, 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.


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


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号