Why there is no option to add custom url converters to blueprints like for main app?

StackOverflow https://stackoverflow.com/questions/20977449

  •  25-09-2022
  •  | 
  •  

Frage

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

War es hilfreich?

Lösung

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)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top