猿问

将两个python装饰器合并为一个

我想合并两个装饰器,因为它们非常相似,不同之处在于如何处理未经身份验证的用户。我希望有一个可以与参数一起调用的装饰器。


# Authentication decorator for routes

# Will redirect to the login page if not authenticated

def 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 authenticated

def 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.requireAuthentication

def day():

    ...


@get('/night/')

@helpers.requireAuthenticationJSON

def night():

    ...

我更喜欢这样:


@get('/day/')

@helpers.requireAuthentication()

def day():

    ...


@get('/night/')

@helpers.requireAuthentication(json = True)

def night():

    ...

我在使用Bottle框架的python 3.3上。有可能做我想做的吗?如何?


慕容708150
浏览 219回答 3
3回答

胡说叔叔

只需添加另一个包装即可捕获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,它的返回值将用作该@行所应用功能的实际装饰器。
随时随地看视频慕课网APP

相关分类

Python
我要回答