Python装饰器错误处理

2024-04-25 02:10:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建瓶托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

句柄身份验证错误函数:

^{pr2}$

一切都很好,除了我安装了瓶子插件来捕捉异常并将它们转换成所需的JSON,API响应有content typeapplication/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=callback(*a,**kw)

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

但是如果我输入return handle_auth_error(e),函数返回dict,而不是函数,我会得到异常dict object is not callable at code line rv = callback(*a, **kw)

如何从decorator返回带参数的函数,而不在decorator中调用它,而在plugin中调用它? 或者如何将异常作为参数传递给插件?在

可能的解决方案是创建自己的函数,使用基于异常名称的“switch”语句来处理每个可能的异常,但我想更具编程性:

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

Tags: 函数插件authapigetreturndef错误
1条回答
网友
1楼 · 发布于 2024-04-25 02:10:22

我觉得你的装饰画写得不对,是不是应该是:

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

相关问题 更多 >