我在 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: handle1() except type2 as e: handle()}我想将这个异常处理保留在一个公共类中(可能是一个 mixin)。需要异常处理的类将继承通用类。将重复的异常处理保留在一个公共类中。我正在使用 python3 和 django1.11 - 基于类的视图
2 回答

隔江千里
TA贡献1906条经验 获得超10个赞
如果您使用的是 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)
以您的方式修改它。供参考访问文档。
添加回答
举报
0/150
提交
取消