Combine two python decorators into one

旧时模样 提交于 2019-12-01 06:33:23

Just add another wrapper to capture the json parameter:

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

I've renamed your original requireAuthentication function to decorator (because that is what that function did, it decorated fn) and renamed the old decorator to wrapper, the usual convention.

Whatever you put after the @ is an expression, evaluated first to find the actual decorator function. @helpers.requireAuthentication() means you want to call requireAuthentication and it's return value is then used as the actual decorator for the function the @ line applies to.

You can create wrapper for both of these decorators:

def requireAuthentication(json=False):
    if json:
        return helpers.requireAuthenticationJSON
    else:
        return helpers.requireAuthentication

Or

import functools
# Authentication decorator for routes
# Will redirect to the login page if not authenticated
def requireAuthentication(json=False):
    def requireAuthentication(fn):
        @functools.wraps(fn)
        def decorator(*args, **kwargs):
            # Is user logged on?
            if "user" in request.session:
                return fn(*args, **kwargs)
            if json:
                 return {
                "exception": "NotAuthorized",
                "error" : "You are not authorized, please log on"
            }
            return redirect('/login?url={0}{1}'.format(request.path, 
                                                       ("?" + request.query_string if request.query_string else '')))
        return decorator
    return requireAuthentication
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!