Django:如何覆盖核心处理程序

时间:2016-11-20 12:47:36

标签: python django inheritance handler middleware

我制作了一个自定义中间件,如果它抛出异常,它会由BaseHandler函数get_response(django.core.handlers.base)自动处理。默认情况下,我的异常ObjectDoesNotExist未得到处理,因此函数handle_uncaught_exception会处理它。但它将所有错误视为500内部服务器(即使它是400 Bad请求)并返回默认的django错误html模板500代码。这是我的代码:

custom_middleware.py:

class CustomMiddleware(object):
"""
custom middleware
"""
def process_request(self, request):
    try:
        # if agent doesn't exists then return json response
        agent = Agent.objects.get(agent_token=agent_token)
    except ObjectDoesNotExist as e:
        raise Exception(exception_code=400, detail=e, response_msg="You are not an authorized agent", request= request_data)

这自动由BaseHandler.get_response()

处理

所以为了解决这个问题,我所做的是继承BaseHandler并覆盖get_response函数,为我的错误添加异常处理程序,并提供 json响应而不是HTML模板。

base.py

from django.core.handlers.base import BaseHandler

class ExceptionHandler(BaseHandler):

    def get_response(self, request):
        my code

但这并没有帮助,因为即使在覆盖之后它也会调用基类方法。

这是追溯:

  File "/webapp/apps/middleware/custom_middleware.py" in process_request
  49.  agent = Agent.objects.get(agent_token=agent_token)

File "lib/python3.4/site-packages/django/db/models/manager.py" in manager_method
  122.  return getattr(self.get_queryset(), name)(*args, **kwargs)

File "lib/python3.4/site-packages/django/db/models/query.py" in get
  387.  self.model._meta.object_name

During handling of the above exception (Agent matching query does not exist.), another exception occurred:

File "lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  123.  response = middleware_method(request)

File "webapp/apps/middleware/request_log.py" in process_request
  54.   raise Exception(exception_code=400, detail=e, response_msg="You are not an authorized agent", request= request_data)

任何帮助

0 个答案:

没有答案