In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "how to catch all exception handling through Django in python". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn "how to catch all exception handling through Django in python".
Overview
Unified exception handling in the project can prevent uncaught exceptions in the code. This paper introduces how to handle the unified exception in the Django project, and then log the project exception information with the status code enumeration class.
Django unified exception handling
In the Django project, you can customize the middleware class to inherit the MiddlewareMixin middleware class under django.middleware.common, rewrite the exception handling logic of the process_exception method, and then register in the middleware under the project configuration for global exception handling.
I write the middleware in the middlewares.py module under the utils package defined by the project.
# roomlewares.pythonopia: *-coding: utf-8-*-# @ Author: Hui# @ Desc: {Project Middleware Module} # @ Date: 2021-09-24 8:18from django.middleware.common import MiddlewareMixinclass ExceptionMiddleware (MiddlewareMixin): "" Unified exception handling Middleware "def process_exception (self, request) Exception): "" uniform exception handling: param request: request object: param exception: exception object: return: "" # exception handling print (exception) return None
For the time being, we simply output the exception to simulate the exception handling. Finally, don't forget to register the middleware in the configuration file. The default configuration file for the django project is settings.py. I just put the configuration file separately under the settings package and changed the file name.
Introduction of process_exception method
The process_exception method is executed only if an exception occurs in the view function. The return value of this method can be a None or a HttpResponse object.
The return value is None, the page will report a 500 status code error, and the view function will not be executed.
If the return value is a HttpResponse object, it is the corresponding response information, and the page will not report an error.
Methods in middleware
The method functions process_request (self,request) before executing the process_view (self,request, view_func, view_args, view_kwargs) view function, and after the process_request method executes the process_exception (self,request, exception) view function, the process_response (self,request, response) view function is executed after an exception occurs in the view function.
The following diagram can better show the logic of the whole process of django.
More middleware details can be found in the Django official documentation.
Unified exception handling specific design
Combine the custom exception and status code enumeration classes to deal with exception log information and business logic.
Custom exception module # exception s. Python init__: *-coding: utf-8-*-# @ Author: Hui# @ Desc: {Project exception module} # @ Date: 2021-09-24 8:14class CommonException (Exception): "Public exception class" def _ _ init__ (self) " Enum_cls): self.code = enum_cls.code self.errmsg = enum_cls.errmsg self.enum_cls = enum_cls # status code enumeration class super (). _ init__ () class BusinessException (CommonException): "business exception class"passclass APIException (CommonException):" interface exception class "" pass custom status code enumeration class " # accounts.pythonium coding, usrbinbinAccord, pythonium-*-coding: utf-8-*-# @ Author: Hui# @ Desc: {Project enumeration class module} # @ Date: 2021-09-23 23:37from enum import Enumclass StatusCodeEnum (Enum): "" status code enumeration class "OK = (0) 'success') ERROR = (- 1, 'error') SERVER_ERR = (500, 'server exception') IMAGE_CODE_ERR = (4001, 'graphic CAPTCHA error') THROTTLING_ERR = (4002, 'frequent access') NECESSARY_PARAM_ERR = (4003, 'missing required parameter') USER_ERR = (4004, 'user name error') PWD_ERR = (4005) 'incorrect password') CPWD_ERR = (4006, 'inconsistent password') MOBILE_ERR = (4007, 'incorrect mobile phone number') SMS_CODE_ERR = (4008, 'incorrect SMS verification code') ALLOW_ERR = (4009, 'unchecked protocol') SESSION_ERR = (4010, 'user not logged in') REGISTER_FAILED_ERR = (4011, 'registration failed') DB_ERR = (5000) 'database error') EMAIL_ERR = (5001, 'mailbox error') TEL_ERR = (5002, 'landline error') NODATA_ERR = (5003,'no data') NEW_PWD_ERR = (5004, 'new password error') OPENID_ERR = (5005, 'invalid openid') PARAM_ERR = (5006,' parameter error') STOCK_ERR = (5007) 'insufficient inventory') @ property def code (self): "get status code"return self.value [0] @ property def errmsg (self):" get status code information "" return self.value [1]
Custom exception classes are used to distinguish between system exceptions and business for separate processing.
Status code enumeration is used to record the corresponding exception information.
The design of status code enumeration class can refer to the information of designing status code by using Python enumeration class skillfully.
The encapsulation of the unified result of response information
Unify the results of front and rear interaction data and abnormal information.
# result.22:10from import StatusCodeEnumclass R: *-coding: utf-8-*-# @ Author: Hui# @ Desc: {Project information returns result module} # @ Date: 2021-09-23 22:10from .enums import StatusCodeEnumclass R (object): "uniform project information returns result class" def _ _ result (self): self.code = None Self.errmsg = None self._data = dict () @ staticmethod def ok (): "" Organization successful response message: return: "r = R () r.code = StatusCodeEnum.OK.code r.errmsg = StatusCodeEnum.OK.errmsg return r @ staticmethod def error ():" group Organizational error response message: return: "" r = R () r.code = StatusCodeEnum.ERROR.code r.errmsg = StatusCodeEnum.ERROR.errmsg return r @ staticmethod def server_error (): "" Organization Server error message: return: "r = R () r .code = StatusCodeEnum.SERVER_ERR.code r.errmsg = StatusCodeEnum.SERVER_ERR.errmsg return r @ staticmethod def set_result (enum): "" Organization response information for corresponding enumeration classes: param enum: status enumeration class: return: "" r = R () r.code = enum.code r.errmsg = Enum.errmsg return r def data (self Key=None, obj=None): "" unify the data returned by the backend "" if key: self._ data [key] = obj context = {'code': self.code,' errmsg': self.errmsg 'data': self._data} return context perfects the unified exception handling logic # unified lewares.python exception handling-*-coding: utf-8-*-# @ Author: Hui# @ Desc: {Project Middleware Module} # @ Date: 2021-09-24 8:18import loggingfrom django.db import DatabaseErrorfrom django.http.response import JsonResponsefrom django.http import HttpResponseServerErrorfrom django.middleware.common import MiddlewareMixinfrom meiduo_mall.utils.result import Rfrom meiduo_mall.utils.enums import StatusCodeEnumfrom meiduo_mall.utils.exceptions import BusinessExceptionlogger = logging.getLogger ('django') class ExceptionMiddleware (MiddlewareMixin): "uniform exception handling middleware"def process_exception (self) Request, exception): "" uniform exception handling: param request: request object: param exception: exception object: return: "" if isinstance (exception, BusinessException): # Business exception handling data = R.set_result (exception.enum_cls). Data () return JsonResponse (data) elif isinstance (exception) DatabaseError): # Database exception r = R.set_result (StatusCodeEnum.DB_ERR) logger.error (r.data (), exc_info=True) return HttpResponseServerError (StatusCodeEnum.SERVER_ERR.errmsg) elif isinstance (exception, Exception): # Server exception handling r = R.server_error () logger.error (r.data () Exc_info=True) return HttpResponseServerError (r.errmsg) return None application scenario registration verification
Let's take a look at a section of registration verification function business logic.
Def verify_params (self Request): "" verify registration information: param request: registration request object: return: response_ret "# accept the parameter self.username = request.POST.get ('username') self.password = request.POST.get (' password') self.confirm_pwd = request.POST.get ('confirm_pwd') Self.mobile = request.POST.get ('mobile') self.allow = request.POST.get (' allow') if not all (all_args): # raise BusinessException (StatusCodeEnum.PARAM_ERR) response_ret = http.HttpResponseForbidden ('parameter error') return response_ret # username 5-20 characters if not re. Match (r'^ [a-zA-Z0-9 _] {5pm 20}' Self.username): response_ret = http.HttpResponseForbidden ('user name is not standard') return response_ret # password 8-20 characters if not re.match (r'^ [a-zA-Z0-9] {8jue 20}' Self.password): response_ret = http.HttpResponseForbidden ('password is not standard') return response_ret # twice password consistency if self.password! = self.confirm_pwd: response_ret = http.HttpResponseForbidden ('two passwords inconsistent') return response_ret # valid mobile phone number if not re. Match (r'^ 1 [3-9]\ d {9} $') Self.mobile): response_ret = http.HttpResponseForbidden ('invalid mobile number') return response_ret # whether to check the user agreement if self.allow! = 'on': response_ret = http.HttpResponseForbidden (' please check the user agreement') return response_ret return response_ret
Handled by throwing exceptions and setting status code enumeration
Def verify_params (self Request): "" verify registration information: param request: registration request object: return: response_ret "# accept the parameter self.username = request.POST.get ('username') self.password = request.POST.get (' password') self.confirm_pwd = request.POST.get ('confirm_pwd') Self.mobile = request.POST.get ('mobile') self.allow = request.POST.get (' allow') # check parameter all_args = [self.username Self.password, self.confirm_pwd, self.mobile, self.allow] if not all (all_args): raise BusinessException (StatusCodeEnum.PARAM_ERR) # username 5-20 characters if not re.match (r'^ [a-zA-Z0-9 _] {5pm 20}' Self.username): raise BusinessException (StatusCodeEnum.USER_ERR) # password 8-20 characters if not re.match (r'^ [a-zA-Z0-9] {8jue 20}' Self.password): raise BusinessException (StatusCodeEnum.PWD_ERR) # twice password consistency if self.password! = self.confirm_pwd: raise BusinessException (StatusCodeEnum.CPWD_ERR) # legitimacy of mobile phone number if not re.match (r'^ 1 [3-9]\ d {9} $') Self.mobile): raise BusinessException (StatusCodeEnum.MOBILE_ERR) # whether to check the user protocol if self.allow! = 'on': raise BusinessException (StatusCodeEnum.ALLOW_ERR)
Reduce try... Except... Code block
For example, when operating on a database, in order to prevent an unexpected exception in the database from causing the system to crash, try is usually added. Except... To record abnormal information. However, if global exception handling is configured, there is no need for management.
# create user try: user = User.objects.create_user (username=self.username, password=self.password, mobile=self.mobile,) except DatabaseError ase: logger.error (e) # with global exception handling user = User.objects.create_user (username=self.username, password=self.password, mobile=self.mobile,)
Note: if you need to process some business information through exception capture, it is inevitable, such as transaction rollback, etc.
The above is all the content of the article "how to catch all exception handling through Django in python". 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.