溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何解決python中Flask裝飾器順序問題

發(fā)布時間:2021-08-05 10:33:17 來源:億速云 閱讀:157 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細講解有關(guān)如何解決python中Flask裝飾器順序問題,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

前言

這個題是用 flask 框架寫的,在 www/bookhub/views/user.py 中, refresh_session 方法存在未授權(quán)訪問漏洞,代碼是這樣寫的:

@login_required
@user_blueprint.route('/admin/system/refresh_session/', methods=['POST'])
def refresh_session():
 pass # 這里省略內(nèi)容

注意看 @login_required 這個裝飾器寫在了 route 裝飾器上面了,導致了 login_required 未調(diào)用。那么,為什么會這樣子呢?

官方文檔

Flask 官方文檔中關(guān)于Login Required Decorator說明 這一節(jié)里面有一行說明:

To use the decorator, apply it as innermost decorator to a view function. When applying further decorators, always remember that the route() decorator is the outermost.

大概意思就是,必須保證 route 裝飾器在最頂層

那么為什么要這樣提示呢?

Python 裝飾器順序說明

本節(jié)內(nèi)容可直接參考: Python 裝飾器執(zhí)行順序迷思

總結(jié)一下就是,裝飾的順序按靠近函數(shù)順序執(zhí)行,從內(nèi)到外裝飾,調(diào)用時由外而內(nèi),執(zhí)行順序和裝飾順序相反。

回過頭來看 Flask

Flask 框架中, route 裝飾器是這么寫的:

def route(self, rule, **options):
 """Like :meth:`Flask.route` but for a blueprint. The endpoint for the
 :func:`url_for` function is prefixed with the name of the blueprint.
 """
 def decorator(f):
  endpoint = options.pop("endpoint", f.__name__)
  self.add_url_rule(rule, endpoint, f, **options)
  return f
 return decorator

route 調(diào)用了 add_url_rule , 對傳入的 f 添加一條 URL 規(guī)則。

所以,按照 python 裝飾器順序:

  1. 如果 @app.route 在內(nèi)層,那么就會把最原始的 view 函數(shù)傳給 add_url_rule , Flask 框架就會添加一條 URL 規(guī)則,指向最原始的 view 函數(shù)。

  2. 如果 @app.route 在外層,那么就會把已經(jīng)被 login_required 裝飾過的 view 函數(shù)傳給 add_url_rule , Flask 框架就會添加一條 URL 規(guī)則,指向已經(jīng)裝飾過的 view 函數(shù)。

下面是兩個例子,來說明:

正確寫法

@user_blueprint.route('/admin/refresh_session/', methods=['POST'])
@login_required
def refresh_session():
 pass

這段代碼相當于:

# 這里沒有裝飾器
def refresh_session():
 pass

login_wrapped = login_required(refresh_session) # login 裝飾器
both_wrapped = app.route('/admin/refresh_session/')(login_wrapped) # route 裝飾器

/admin/refresh_session/ 這條路由指向的實際是 login_wrapped ,這樣就會經(jīng)過 login 檢查

錯誤寫法

@login_required
@user_blueprint.route('/admin/refresh_session/', methods=['POST'])
def refresh_session():
 pass

這段代碼相當于:

# 這里沒有裝飾器
def refresh_session():
 pass

route_wrapped = app.route('/admin/refresh_session/')(refresh_session) # route 裝飾器
login_wrapped = login_required(route_wrapped)  # login 裝飾器

/admin/refresh_session/ 這條路由指向的實際是 refresh_session , 而 login_wrapped 并沒有與路由掛勾,所以不會被調(diào)用。

關(guān)于“如何解決python中Flask裝飾器順序問題”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI