Python 如何捕获像mixin这样的公共类中的所有异常
我在python django应用程序中有基于类的视图。它们中的大多数处理相同类型的异常,如:Python 如何捕获像mixin这样的公共类中的所有异常,python,django,decorator,mixins,Python,Django,Decorator,Mixins,我在python django应用程序中有基于类的视图。它们中的大多数处理相同类型的异常,如: class A{ try: func1() except type1 as e: handle1() except type2 as e: handle() } class B{ try: func2() func3() except type1 as e: han
class A{
try:
func1()
except type1 as e:
handle1()
except type2 as e:
handle()
}
class B{
try:
func2()
func3()
except type1 as e:
handle1()
except type2 as e:
handle()
}
我希望将此异常处理保留在一个公共类中(可能是一个mixin)。需要异常处理的类将继承公共类
将重复的异常处理保留在公共类中。我使用的是python3和django1.11-基于类的视图您可以将异常处理提取到基类,并更改派生类中的实现:
In [15]: import abc
In [16]: class Base:
...: def run(self):
...: try:
...: self.do_run()
...: except:
...: print('failed')
...:
...: @abc.abstractmethod
...: def do_run(self):
...: ...
...:
In [17]: class Foo(Base):
...: def do_run(self):
...: print('run foo')
...:
In [18]: class Bar(Base):
...: def do_run(self):
...: print('fail bar')
...: raise Exception()
...:
In [19]: f = Foo()
In [20]: f.run()
run foo
In [21]: b = Bar()
In [22]: b.run()
fail bar
failed
如果您使用的是django类的基本视图,那么可以重写
dispatch
并创建一个mixin。在django中,基于类的视图分派方法接收请求并最终返回响应
你可以做类似的事情-
class ExceptionHandlingMixin(object):
def dispatch(self, request, *args, **kwargs):
try:
func1()
except type1 as e:
handle()
except type2 as e:
handle()
return super(ExceptionHandlingMixin, self).dispatch(request, *args, **kwargs)
用你的方式修改这个。参考访问。
导入abc
表示“导入抽象基类模块”。@abc.abstractmethod
所需。有关更多信息,请参见此处: