异常情况下执行的动作装饰器
项目描述
此包旨在提供在异常情况下执行自定义动作的装饰器。让我们看看一个例子
首先,我们需要一个包含一些方法的对象。我们将这些方法装饰为 PrintOnFailure 装饰器。这个简单的示例装饰器在发生异常时打印给定的消息。
>>> from failureaction import ConflictError >>> from failureaction import PrintOnFailure >>> class TestOb(object): ... ... @PrintOnFailure(msg='Some numeric calculation went wrong!') ... def divide(self, a, b): ... return a/b ... ... @PrintOnFailure() ... def doraise(self): ... raise ConflictError
我们有两个方法。一个(除法)执行两个数字的数值除法,另一个引发一个自定义定义的ConflictError。现在让我们看看这些方法的作用
>>> ob = TestOb() >>> ob.divide(4, 2) 2>>> ob.divide(42, 0) Some numeric calculation went wrong!>>> ob.doraise() Traceback (most recent call last): ... ConflictError
模块提供的 ActionOnFailure 装饰器旨在由自定义类覆盖。就像这样
>>> from failureaction import ActionOnFailure >>> class MailOnFailure(ActionOnFailure): ... ... def __init__(self, subject): ... self.subject = subject ... ... def _doaction(self, context, e): ... """ send a mail, if an exception was raised """ ... print "Subject:", self.subject ... print e>>> class TestOb2(object): ... ... @MailOnFailure(subject='An error occured') ... def critical(self): ... import _not_existent_hopefully_>>> ob2 = TestOb2() >>> ob2.critical() Subject: An error occured No module named _not_existent_hopefully_