In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how to use Django and DRF to achieve global exception handling, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
The goal achieved
Without DRF, we only need to add a middleware to Django to solve the problem of handling global exceptions, but DRF will help us handle some exceptions and automatically return to the client, so we need to coordinate the exception handling strategies of the two.
At the same time, we want to be able to use Django's admin for some background data viewing and modification, so it's best to keep the internal exception handling behavior of admin.
The objectives of this paper are as follows:
Preserve the exception handling behavior of admin that comes with Django
Intercept DRF exceptions and handle global exception behavior
Intercept Django exceptions other than those of DRF and handle global exception behavior
The solution of global exception interception in DRF
First of all, the exceptions of DRF are inherited from the class APIException, and the exceptions run by DRF will be intercepted by the exception handler exception_handler (the position of this function is in / python3.7/site-packages/rest_framework/views.py).
Let's take a closer look at the source code of this function:
Def exception_handler (exc, context): "" Returns the response that should be used for any given exception. By default we handle the REST framework `APIException`, and also Django's built-in `Http404` and `PermissionDenied` exceptions. Any unhandled exceptions may return `None`, which will cause a 500Exception` "" If isinstance (exc, Http404): exc = exceptions.NotFound () elif isinstance (exc, PermissionDenied): exc = exceptions.PermissionDenied () if isinstance (exc, exceptions.APIException): headers = {} if getattr (exc, 'auth_header', None): headers [' WWW-Authenticate'] = exc.auth_header if getattr (exc, 'wait') None): headers ['Retry-After'] ='% d'% exc.wait if isinstance (exc.detail, (list, dict)): data = exc.detail else: data = {'detail': exc.detail} set_rollback () return Response (data, status=exc.status_code, headers=headers) return None
Through the document signature of this function, we know that DRF handles all exception classes inherited from APIException, and additionally handles Django's built-in Http404 and PermissionDenied exceptions, and returns the handling results of these exceptions to the foreground.
If it is not within the scope of these processes, the function returns None, which throws a 500 server error exception to Django.
DRF supports configuring exception handlers separately, so the first step now specifies the location of custom exception handlers in setting:
REST_FRAMEWORK = {'EXCEPTION_HANDLER':' server.exception.exception_globe.globe_exception_handler'}
Then we define our own exception handler:
The first step is to call DRF's own exception handling function, the second step is to handle the exceptions intercepted by DRF, and the third step is to throw other exceptions to Django handling.
Def globe_exception_handler (exc, context): "Below is the global exception handler of drf Http404 / PermissionDenied / APIException"# Call REST framework's default exception handler response = exception_handler (exc, context) request = context ['request'] # Exceptions form DRF and Django built-in `Http404` and `PermissionDenied`if response is not None: if isinstance (response.data, list): msg =' '.join (response.data) elif isinstance (response.data, str): msg = response.data else: msg = 'Sorry, we make a mistake (* thanks thanks)!' Ex_data = {"msg": msg, "error_code": 1000, "request": request.path} return JsonResponse (data=ex_data, status=response.status_code) # Exceptions from others # if response is None, trigger the above ExceptionGlobeMiddleware return responseDjango exception handling scheme directly
From the results of the previous step, we know that we throw to Django the exceptions that DRF cannot handle, and Django supports global exception handling by defining middleware, so we only need to define a middleware for Django global exception handling and configure the middleware to the MIDDLEWARE array in the setting file.
Try: from django.utils.deprecation import MiddlewareMixin # Django 1.10.xexcept ImportError: MiddlewareMixin = object # Django 1.4.x-Django 1.9.xclass ExceptionGlobeMiddleware (MiddlewareMixin): "" Below is the global exception handler of django "def process_exception (self, request) Exception): # directly throw django admin's exception if str (request.path) .startswith ('/ admin/'): return None # catch other exceptions Directly return 500 ex_data = {"msg": "Sorry, we make a mistake (* roommates)!", "error_code": 1000, "request": request.path} return JsonResponse (data=ex_data, status=500)
It is worth noting that we can get the request object in the handler of the middleware, so we can get the url requested by the user through this object, so that we can get those requests from the admin that comes with Django by judging the url.
The reference code is as follows:
# throw django admin exception if str (request.path) .startswith ('/ admin/') directly: return None is all the contents of the article "how to use Django and DRF to implement global exception handling". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.