1. b.93z.org
  2. Notes

Writing Werkzeug routing converter

Recently I finished project, where I needed to support legacy URLs with paths like this:


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(
        # ...
    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.

© 2008–2017 93z.org