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

use*_*006 6 python decorator flask

我想让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
Run Code Online (Sandbox Code Playgroud)

然后,基本上都/section/one/section/two运行my_method()在执行代码之前route_one()route_two().

有没有办法做到这一点?

Mig*_*uel 11

您可以使用before_request装饰器来获取蓝图.像这样:

@section.before_request
def my_method():
    do_stuff
Run Code Online (Sandbox Code Playgroud)

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

  • @SamRedway 可以,但是你必须为每条路线添加一个装饰器。如果您在应用程序或蓝图级别使用“before_request()”装饰器,则只需指定一次。 (2认同)