问题描述
在此帖子和官方文档,我们看到了如何为主应用程序对象添加自定义网址转换器.这是一个简短的示例:
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...
推荐答案
您无法在蓝图上使用自定义URL转换器的技术原因是,与应用程序不同,蓝图没有URL映射.
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.
当您使用蓝图的 route
装饰器或 add_url_map()
方法时,所有蓝图所做的工作就是记录以后在时调用这些方法的应用程序版本的意图.register_blueprint()
被调用.
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.
我不确定允许使用蓝图特定的URL转换器是否有好处.但是我认为允许蓝图安装应用程序范围的转换器是合理的.例如,这可以使用与其他蓝图应用程序范围内的处理程序相同的技术,例如 before_app_request
.
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)
这篇关于为什么没有选择将自定义url转换器添加到蓝图(如主应用程序)的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!