我是Python的初学者,我需要装饰器方面的帮助。我正在编写一些方法,这些方法调用使用swagger生成的其他方法。基本上所有这些摇摇欲坠的方法都具有GET API。我在代码中需要做的就是调用那些swagger方法并返回值。我正在寻找优化方法,而不是为每个API编写相同类型的方法。我遇到了可以在这种情况下使用的装饰器。但是我的实现没有给出期望的结果
def get_component_info(self, func):
def inner():
data = None
try:
ret = func()
if ret.status == 200:
log.info('ret ' + str(ret))
else:
logging.error('Error: ' + str(ret.text))
except Exception as e:
logging.error(" failed with error " + str(e.reason) +
" and error code " + str(e.status))
finally:
return data
return inner()
def get_firewall_info(self):
return self._monitor.list_firewall_monitors_with_http_info() <-- swagger method
def get_firewall_info_caller(self):
get_firewall_info = self.get_component_info(self.get_firewall_info())
但是上面的实现总是返回None,因为它从不执行self._monitor.list_firewall_monitors_with_http_info()
,但是测试没有失败
如果您帮助我解决此问题,那么我可以使用它来获取服务器信息,身份验证信息,网络信息等。如果无法使用装饰器,还有什么我可以用来优化它的..?
谢谢
装饰器通常是将第二个函数作为参数,然后定义并返回第三个函数的函数,该函数在更改其输入和/或输出时调用第二个函数。看来您比我作为一个初学者在此方面的处理要好。
def decorator(func):
def inner(*args, **kwargs):
# Do stuff here...
value = func(*args, **kwargs)
# ...or here.
return value
return inner
我建议装饰器的唯一更改不是调用inner
并返回结果,而是返回函数本身。进行此更改时,必须在返回后立即调用要返回的函数。
def get_component_info(self, func):
def inner():
# ...
return inner
def get_firewall_info_caller(self):
# You will now want to call the `inner` function after you get
# it from `get_component_info`.
get_firewall_info = self.get_component_info(...)()
看来,您的错误的核心是您没有向提供功能get_component_info
;您将提供调用该函数的结果。我认为将代码更改为不调用get_firewall_info
应该可以修复您的代码。
def get_firewall_info_caller(self):
# You don't want to call the function you're providing to a
# decorator, since it's expecting the function not the result.
get_firewall_info = self.get_component_info(self.get_firewall_info)()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句