本文介绍了覆盖烧瓶蓝图中的路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一张蓝图,定义了很多有用的路线,但我无法控制它(不能以任何方式更改它的代码)尝试在不同的应用程序中重用它,但蓝图的一个终结点必须超载。我如何才能做到这一点?

我尝试将新路线添加到蓝图的现有路线之上:

@blueprint.route('/my/route', methods=['PUT', 'POST'])
def my_new_view_func(program, project):
    # some new behavior for the endpoint

因此,app.url_map.iter_rules()中存在重复的url_Rule:

<Rule '/my/route' (PUT, POST) -> my_view_func>,
<Rule '/my/route' (PUT, POST) -> my_new_view_func>,

并在请求/my/route旧查看器my_view_func时执行

我可以以某种方式摆脱旧的URL规则吗?或者也许有更好的方法来覆盖路由?

推荐答案

我找到了两个解决方案。第一个

from flask import Flask, Blueprint


simple_page = Blueprint('simple_page', __name__, )


@simple_page.route('/my/route/')
def my():
    # for example it's a registered route somewhere...
    return 'default'


@simple_page.route('/my/route/')
def new_my():
    # new endpoint / should works instead my()
    return 'new'

# map of views which we won't register in Flask app
# you can store this somewhere in settings
SKIP_VIEWS = (
    # route, view function
    ('/my/route/', my, ),
)


class CustomFlask(Flask):

    def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
        # Flask registers views when an application starts
        # do not add view from SKIP_VIEWS
        for rule_, view_func_ in SKIP_VIEWS:  # type: str, func
            if rule_ == rule and view_func == view_func_:
                return
        return super(CustomFlask, self).add_url_rule(rule, endpoint, view_func, **options)


app = CustomFlask(__name__)
app.register_blueprint(simple_page)
app.run(debug=True)

第二种方式

two.py-带端点的默认蓝图

from flask import Blueprint

bp_two = Blueprint('simple_page2', __name__, )


@bp_two.route('/my/route/')
def default():
    return 'default'

test.py-您的蓝图+APP

from flask import Flask, Blueprint

from two import bp_two

your_bp = Blueprint('simple_page', __name__, )


@your_bp.route('/my/route/')
def new_route():
    return 'new'


app = Flask(__name__)
# register blueprint and turn off '/my/route/' endpoint
app.register_blueprint(bp_two, **{'url_defaults': {'/my/route/': None}})
app.register_blueprint(your_bp)

app.run(debug=True)

运行应用程序。打开/my/route/。您将看到默认终结点不是Add/Works。

希望这对您有帮助。

这篇关于覆盖烧瓶蓝图中的路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-20 04:35