gpt4 book ai didi

python - Flask:如果字段不存在,则 current_app AttributeError

转载 作者:行者123 更新时间:2023-12-01 06:40:50 60 4
gpt4 key购买 nike

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

例如:

if current_app.exists is None:

给予:

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

try/catch 是处理这个问题的正确方法吗?

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'}

最佳答案

您可以使用内置函数 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'

关于python - Flask:如果字段不存在,则 current_app AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59461647/

60 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com