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

不羁岁月 提交于 2021-01-27 21:34:49

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/20977449/why-there-is-no-option-to-add-custom-url-converters-to-blueprints-like-for-main

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!