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

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

我想让Flask Blueprint在执行任何路由之前始终运行一个方法.我没有用自定义装饰器装饰我的蓝图中的每个路线方法,而是希望能够做到这样的事情: def my_method(): do_stuffsection = Blueprint(section, __name__)# Register my_method() as a setup method th

我想让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

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

本文来自网络,不代表云浮站长网立场。转载请注明出处: https://www.0766zz.com/html/kaifa/python/20210111/14380.html
上一篇
下一篇

作者: dawei

【声明】:云浮站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

返回顶部