簡體   English   中英

Flask:如何在藍圖中的每個路徑之前運行方法?

[英]Flask: How to run a method before every route in a blueprint?

我想讓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將運行my_method()在執行代碼之前route_one()route_two()

有沒有辦法做到這一點?

您可以使用before_request裝飾器來獲取藍圖。 像這樣:

@section.before_request
def my_method():
    do_stuff

這會自動注冊要在屬於藍圖的任何路由之前運行的函數。

你可以使用before_request

@section.before_request
def before_request():
    do_stuff

http://flask.pocoo.org/docs/0.10/api/#flask.Flask.before_request

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM