我希望python&中的函数超时(rest API调用)因为我正在关注this所以回答。
我已经有一个现有的代码结构,我希望有一个超时装饰器。我在“.txt”文件中定义了超时秒数。将它作为dict传递给main函数。类似的东西:
class Foo():
def __init__(self, params):
self.timeout=params.get['timeout']
....
....
@timeout(self.timeout) #throws an error
def bar(arg1,arg2,arg3,argn):
pass
#handle timeout for this function by getting timeout from __init__
#As answer given in SO ,
#I need to use the self.timeout, which is throwing an error:
***signal.alarm(seconds)
TypeError: an integer is required***
#And also
***@timeout(self.timeout)
NameError: name 'self' is not defined***
@timeout(30) #Works fine without any issue
def foo_bar(arg1,arg2,arg3,argn):
pass
我缺少什么?
答案 0 :(得分:0)
在A
,self
未定义,因为装饰器在方法之外,但self仅存在于方法内:
@timeout(self.timeout) # <== A
def bar(self,arg1,arg2,arg3):
pass
您可以尝试将barTimeout
属性设置为__init__
:
class Foo():
def bar(self,arg1,arg2,arg3):
pass
def __init__(self, params):
self.timeout=params.get('timeout')
self.barTimeout = timeout(self.timeout)(self.bar)
Foo({'timeout':30}).barTimeout(1,2,3)