为了账号安全,请及时绑定邮箱和手机立即绑定

将两个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 关注
  • 217 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号