Python装饰器错误处理

时间:2017-06-26 15:57:02

标签: python plugins decorator bottle

我正在创建瓶托API,我想在某些端点使用函数装饰器来验证用户身份。装饰者代码是:

def authenticating_decorator(func):
    def wrapper():
        try:
            '''
            auth user before execution of the required code
            if user is not authenticated bottle.HTTPError is raised
            '''
            auth()  
            return func
        except HTTPError as e:
            return handle_auth_error  

    return wrapper()

return authenticating_decorator

处理身份验证错误功能:

def handle_auth_error(error):
    return {
        "code": error.status_code,
        "name": error.body.get('name'),
        "description": error.body.get('description')
    }

除了我安装了瓶插件以捕获异常并将其转换为所需的JSON并且API响应具有内容类型应用/ json

之外,一切正常

auth 方法发生异常时,API以已知的html格式返回错误,因为它以某种方式跳过了我的错误插件。 (我在使用插件和装饰器时,并不完全了解应用程序流程)

我的错误插件的调用方法:

def __call__(self, callback):
    def wrapper(*a, **kw):
        try:
            rv = callback(*a, **kw)
            return rv
        except HTTPError as e:
            response.status = e.status_code
            return {
                "code": e.status_code,
                "name": e.body.get('name'),
                "description": e.body.get('description')
            }
    return wrapper

我的观点是我必须将函数传递给插件,因为行 rv =回调(* a,** kw)

因为我在decorator中的auth()方法中有多种类型的异常,所以我希望将异常作为参数传递给装饰器中的handle_auth_error

但是如果我键入return handle_auth_error(e)函数返回dict,而不是函数,我得到异常dict对象在代码行rv = callback(*a, **kw)无法调用

如何在装饰器中使用参数返回函数,而不是在装饰器中调用它,而是在插件中调用它? 或者如何将异常作为参数传递给插件?

可能的解决方案是使用' switch'创建自己的功能来处理每个可能的异常。基于异常名称的语句,但我想以更有条理的方式进行:

 return {
     'HEADER_MISSING': handle_header_missing_exception,
     'TOKEN_EXPIRED': handle_expired_token_exception,
      etc ... : etc...
            }.get(e.body.get('name'))

1 个答案:

答案 0 :(得分:0)

我认为你的装饰者写得不正确,不应该是:

def authenticating_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kw):
        try:
             '''
            auth user before execution of the required code
            if user is not authenticated bottle.HTTPError is raised
            '''
            auth()  
            return func(*args, **kw) #calling func here
        except HTTPError as e:
            return handle_auth_error(e)  #calling the handle_auto_error here

return wrapper #notice - no call here, just return the wrapper
相关问题