亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將兩個python裝飾器合并為一個

將兩個python裝飾器合并為一個

慕容708150 2021-03-31 00:11:21
我想合并兩個裝飾器,因為它們非常相似,不同之處在于如何處理未經身份驗證的用戶。我希望有一個可以與參數一起調用的裝飾器。# Authentication decorator for routes# Will redirect to the login page if not authenticateddef requireAuthentication(fn):    def decorator(**kwargs):        # Is user logged on?        if "user" in request.session:            return fn(**kwargs)        # No, redirect to login page        else:            redirect('/login?url={0}{1}'.format(request.path, ("?" + request.query_string if request.query_string else '')))    return decorator# Authentication decorator for routes# Will return an error message (in JSON) if not authenticateddef requireAuthenticationJSON(fn):    def decorator(**kwargs):        # Is user logged on?        if "user" in request.session:            return fn(**kwargs)        # No, return error        else:            return {                "exception": "NotAuthorized",                "error" : "You are not authorized, please log on"            }    return decorator目前,我正在將這些裝飾器用于特定的路線,例如@get('/day/')@helpers.requireAuthenticationdef day():    ...@get('/night/')@helpers.requireAuthenticationJSONdef night():    ...我更喜歡這樣:@get('/day/')@helpers.requireAuthentication()def day():    ...@get('/night/')@helpers.requireAuthentication(json = True)def night():    ...我在使用Bottle框架的python 3.3上。有可能做我想做的嗎?如何?
查看完整描述

3 回答

?
胡說叔叔

TA貢獻1804條經驗 獲得超8個贊

只需添加另一個包裝即可捕獲json參數:


def requireAuthentication(json=False):

    def decorator(fn):

        def wrapper(**kwargs):

            # Is user logged on?

            if "user" in request.session:

                return fn(**kwargs)


            # No, return error

            if json:

                return {

                    "exception": "NotAuthorized",

                    "error" : "You are not authorized, please log on"

                }

            redirect('/login?url={0}{1}'.format(request.path, ("?" + request.query_string if request.query_string else '')))

        return wrapper

    return decorator

我已將您的原始requireAuthentication函數重命名為decorator(因為該函數所做的是它的修飾fn),并將舊函數重命名decorator為wrapper,這是通常的約定。


放在表達式之后的@任何內容,都首先求值以找到實際的裝飾器函數。@helpers.requireAuthentication()表示您要調用requireAuthentication,它的返回值將用作該@行所應用功能的實際裝飾器。


查看完整回答
反對 回復 2021-04-01
  • 3 回答
  • 0 關注
  • 232 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號