django应用程序,用于在django rest框架后端返回一致、详细且易于解析的错误消息。
hipo-drf-exceptions的Python项目详细描述
HIPO DRF例外
一个Django应用程序,用于在Django Rest Framework后端返回一致、详细且易于分析的错误消息。
目录
安装
使用pip、pipenv或poetry可以获得hipo异常的稳定版本:
pip install hipo-drf-exceptions
用法
处理程序
您需要设置django project settings.py文件的EXCEPTION_HANDLER
设置。
REST_FRAMEWORK = {
..
'EXCEPTION_HANDLER': 'hipo_drf_exceptions.handler',
}
错误响应示例
字段错误
在模型级别进行验证,并在需要时提高ValidationError
。
fromdjango.core.exceptionsimportValidationErrorclassInvitation(models.Model):email=models.EmailField(unique=True)defsave(self,*args,**kwargs):ifUser.objects.filter(email=self.email).exists():raiseValidationError({"email":_("Email is already registered.")})super().save(*args,**kwargs)
如果视图或序列化程序遇到ValidationError
,则响应如下:
{"type":"ValidationError","detail":{"email":["Email is already registered."]},"fallback_message":"'email' has an error. Email is already registered."}
非现场错误
实现自己的错误类。
fromhipo_drf_exceptionsimportBaseAPIExceptionclassProfileCredentialError(BaseAPIException):default_detail=_('Profile credentials are not correct.')
需要时引发错误。
classAuthenticationView(GenericAPIView):defpost(self,request,*args,**kwargs):..ifnotprofile.check_password(password):raiseProfileCredentialError()..
回答如下:
{"type":"ProfileCredentialError","detail":{"non_field_errors":["Profile credentials are not correct."]},"fallback_message":"Profile credentials are not correct."}
支架
请open an issue支持。
贡献
请使用Github Flow投稿。创建分支、添加提交和open a pull request。