2

In this post and in official docs we saw how to add custom url converters for main app object. Here is short example:

app = Flask(__name__)
app.url_map.converters['list'] = ListConverter

But how to do it for blueprints? This global (app level) custom converter is unavailable for blueprints. In source code I haven't found such posibility...

Community
  • 1
  • 1
Vitalii Ponomar
  • 10,686
  • 20
  • 60
  • 88

1 Answers1

2

The technical reason why you can't have custom URL converters on a blueprint is that unlike applications, blueprints do not have a URL map.

When you use the blueprint's route decorator or add_url_map() method all the blueprint does is record the intention to call the application versions of these methods later when register_blueprint() is called.

I'm not sure there is a benefit in allowing blueprint specific url converters. But I think it would be reasonable to allow a blueprint to install an app wide converter. That could use the same techniques as other blueprint app-wide handlers, like before_app_request, for example.

def add_app_url_converter(self, name, f):
    self.record_once(lambda s: s.app.url_map.converters[name] = f
    return f

Blueprint.add_app_url_converter = add_app_url_converter

# ...

bp = Blueprint('mybp', __name__)
bp.add_app_url_converter('list', ListConverter)
Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152
  • 1
    O, it's possible to add all blueprints wide converters! All we need is to register such converter for app and only after that to register all blueprints (not vice versa as I did) – Vitalii Ponomar Jan 09 '14 at 09:24