[Flask] URL Map Converters

jnnk hi at jnnkb.eu
Fri Dec 3 07:54:04 EST 2021

Hey everybody,

I yesterday tried using an IDSlugConverter similar to this <https://stackoverflow.com/questions/27760307/create-a-url-with-an-articles-title> with a current version of Werkzeug, which worked without any problems until 0.16.0. Unfortuantly any version >= 1.0.0 leads to the following error:

  File "<werkzeug routing>", line 1, in <builder:'/files/<id_slug:id>'>
  File "test_urlmap_converter/flask_app.py", line 20, in to_url
    return f"{value.id}/{value.filename}"
AttributeError: 'int' object has no attribute ‚id‘
I create the following minimal example to illustrate the problem. The error occurs when navigating to /files/3/hey.txt.

from flask import Flask, url_for
from werkzeug.routing import BaseConverter

class File:
    def __init__(self, id_, filename):
        self.id = id_
        self.filename = filename

class IDSlugConverter(BaseConverter):
    """Matches an int id and optional slug, separated by "/"."""

    regex = r"-?\d+(?:/[\w\-]*.\w*)?"

    def to_python(self, value):
        return int((value.split("/"))[0])

    def to_url(self, value):
        return f"{value.id}/{value.filename}"

app = Flask(__name__)
app.url_map.converters["id_slug"] = IDSlugConverter

def index():
    url = url_for("serve_file", id=File(3, "hey.txt"))
    return f'<a href="{url}">Bild</a>'

def serve_file(id):
    return "fancy file"
It seems like these converters now require that to_python and to_url are inverses. Is this intended? Since I’m using this with different model classes I otherwise would have to use some magic like below to prevent circular imports. (See attached app.zip)

def __init__(self, url_map, model):
    module, variable = model.rsplit(".", 1)
    self.model = getattr(sys.modules[module], variable)
With kind regards,


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/flask/attachments/20211203/3f89f2dc/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: app.zip
Type: application/zip
Size: 10012 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/flask/attachments/20211203/3f89f2dc/attachment.zip>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/flask/attachments/20211203/3f89f2dc/attachment-0001.html>

More information about the Flask mailing list