烧瓶:如果字段不存在,则为current_app AttributeError

时间:2019-12-23 21:50:38

标签: python flask decorator

我尝试为Flask创建两个装饰器,以装饰一个简单的函数。两个装饰器都必须有权访问current_app上的相同字段/属性。装饰函数也需要访问该相同属性。但是我想测试该字段是否已经存在,并在任一装饰器中获取其值。如果存在,测试存在确实可以,但是如果尚不存在,则返回AttributeError。例如:如果该字段不存在,则测试“无”或使用hasattr / getattr会给出AttributeError。

例如:

if current_app.exists is None:

赠予:

AttributeError: 'Flask' object has no attribute 'exists'

尝试/捕捉正确的方式来处理此问题吗?

def first(org_func):
    @wraps(org_func)
    def decorated_function(*args, **kwargs):
        try:
            current_app.exists = current_app.exists + ' and then first'
        except AttributeError:
            current_app.exists = 'first'
        print(current_app.exists)
        return org_func(*args, **kwargs)
    return decorated_function

def second(org_func):
    @wraps(org_func)
    def decorated_function(*args, **kwargs):
        try:
            current_app.exists = current_app.exists + ' and then second'
        except AttributeError:
            current_app.exists = 'second'
        print(current_app.exists)
        return org_func(*args, **kwargs)
    return decorated_function

@first    
@second  
def get(self):
    print('original function calling ' + current_app.exists)
    return {'message': 'ok'}

1 个答案:

答案 0 :(得分:1)

您可以为此使用内置函数hasattr。它与装饰器的作用基本相同

hasattr(obj, name, /)
    Return whether the object has an attribute with the given name.

    This is done by calling getattr(obj, name) and catching AttributeError.

例如:

if hasattr(current_app, 'exists'):
    print("current_app has 'exists' attribute")
else:
    print("current_app does not have 'exists' attribute")

或者,您可以将getattr与默认值一起使用,例如:

exists_first = getattr(current_app, 'exists', 'first')
# if current_app has an 'exists' attribute, then exists_first == current_app.exists
# if current_app does NOT have an 'exists' attribue, then exists_first == 'first'
exists_second = getattr(current_app, 'exists', 'second')
# if current_app has an 'exists' attribute, then exists_second == current_app.exists
# if current_app does NOT have an 'exists' attribue, then exists_second == 'second'