加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Flask:如何在蓝图中的每个路径之前运行方法?

发布时间:2020-12-16 23:20:24 所属栏目:Python 来源:网络整理
导读:我想让Flask Blueprint在执行任何路由之前始终运行一个方法.我没有用自定义装饰器装饰我的蓝图中的每个路线方法,而是希望能够做到这样的事情: def my_method(): do_stuffsection = Blueprint('section',__name__)# Register my_method() as a setup method
我想让Flask Blueprint在执行任何路由之前始终运行一个方法.我没有用自定义装饰器装饰我的蓝图中的每个路线方法,而是希望能够做到这样的事情:
def my_method():
    do_stuff

section = Blueprint('section',__name__)

# Register my_method() as a setup method that runs before all routes
section.custom_setup_method(my_method())

@section.route('/two')
def route_one():
    do_stuff

@section.route('/one')
def route_two():
    do_stuff

然后基本上/ section / one和/ section / two将在执行route_one()或route_two()中的代码之前运行my_method().

有没有办法做到这一点?

解决方法

您可以使用 before_request装饰器来获取蓝图.像这样:
@section.before_request
def my_method():
    do_stuff

这会自动注册要在属于蓝图的任何路由之前运行的函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读