Recently I finished project, where I needed to support legacy URLs with paths like this:
/path/to/something/741,2345,2858739,991,3241,2556,3453.aspx
Project uses Werkzeug’s routing, so the only thing I needed to do is to write converter and then somehow handle values in views.
import re
from werkzeug.routing import BaseConverter, ValidationError
class IntListConverter(BaseConverter):
def __init__(self, url_map, separator):
super(IntListConverter, self).__init__(url_map)
self.regex = r'(\d%s?)+' % re.escape(separator)
self.separator = separator
def to_python(self, value):
values = value.strip(self.separator).split(self.separator)
return map(int, values)
def to_url(self, values):
return self.separator.join(map(str, values))
Then I added rule and converter to URL map:
url_map = Map(
[
# ...
Rule('/path/to/something/<intlist(separator=","):values>.aspx',
endpoint='someapp/someview'),
],
strict_slashes=True,
converters={'intlist': IntListConverter},
)
You can go on and create ListConverter
that takes additional type_
argument to convert each value of list to some Python type.
This blog is about things I encounter while doing web and non-web software development.