我正在尝试使用 https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 来decorator
捕获cached_property
异常
https://pypi.python.org/pypi/cached-property
我想做如下简单的事情,但这不起作用
from pprint import pprint
import time
from cached_property import cached_property
class MyException(Exception):
pass
def catch_my_exceptions(fn):
def wrapped(*args, **kwargs):
try:
return fn(*args, **kwargs)
except MyException as e:
cls = args[0]
err = 'Found error at {}: {}'.format(time.asctime(), e)
cls.error_msgs.append(err)
print(err)
return
return wrapped
class Foo(object):
def __init__(self):
self.vars = {}
@cached_property
@catch_my_exceptions
def is_cache_working(self):
self.vars[time.asctime()] = True
time.sleep(3)
print('running cache runner')
return time.asctime()
fo = Foo()
for i in range(3):
print(fo.is_cache_working)
pprint(fo.vars)
# This doesn't trigger caching
running cache runner
Thu Feb 23 21:45:15 2017
{'Thu Feb 23 21:45:11 2017': True}
running cache runner
Thu Feb 23 21:45:18 2017
{'Thu Feb 23 21:45:11 2017': True, 'Thu Feb 23 21:45:15 2017': True}
running cache runner
Thu Feb 23 21:45:21 2017
{'Thu Feb 23 21:45:11 2017': True,
'Thu Feb 23 21:45:15 2017': True,
'Thu Feb 23 21:45:18 2017': True}
# Current solution that works:
我对此的破解是执行以下操作。有人可以建议我一个更好的方法。还有我如何将例外列表传递给这个my_cached_decorator
import time
from pprint import pprint
from cached_property import cached_property
class MyException(Exception):
pass
class my_cached_property(cached_property):
def __init__(self, func):
super(self.__class__, self).__init__(func)
def __get__(self, obj, cls):
try:
super(self.__class__, self).__get__(obj, cls)
except MyException as e:
err = 'Found error at {}: {}'.format(time.asctime(), e)
print(err)
value = obj.__dict__[self.func.__name__] = None
return value
class Foo(object):
def __init__(self):
self.vars = {}
@my_cached_property
def is_cache_working(self):
self.vars[time.asctime()] = True
time.sleep(3)
print('running cache runner')
raise MyException('fooobar')
return time.asctime()
fo = Foo()
for i in range(3):
print(fo.is_cache_working)
pprint(fo.vars)