【问题标题】:Raising a custom 400 bad request in a Rest API using django and django rest framework使用 django 和 django rest 框架在 Rest API 中引发自定义 400 错误请求
【发布时间】:2019-03-17 17:32:54
【问题描述】:

我想在引发 HTTP 400 错误时返回自定义错误。

这是我的模型:

class User(models.Model):
      fullname = models.CharField(max_length=100)
      phone = models.CharField(max_length=50, unique=True)
      password = models.CharField(max_length=50, default='SOME STRING')

这是我的序列化程序类:

class UserSerializer(serializers.ModelSerializer):
      class Meta:
           model = User
           fields = ('id', 'fullname', 'phone', 'password')

这是我在视图类中的课程:

 class RegisterUsers(generics.CreateAPIView):
.
.
.
 serializer = UserSerializer(data={
            "fullname": fullname,
            "phone": phone,
            "password": password
        }
    )

          if not serializer.is_valid(raise_exception=True):
              return

如果我尝试使用相同的号码注册两次,则会引发 400 bad request 错误,如下图所示:

我想捕获错误并将其解析为如下所示的自定义响应:

谁能帮我解决这个问题? 提前致谢。

【问题讨论】:

  • 如果有帮助,您应该接受答案

标签: django python-3.x django-rest-framework


【解决方案1】:

您可以覆盖 DRF 自定义异常处理方法:

from rest_framework.views import exception_handler
from rest_framework.exceptions import ValidationError


def base_exception_handler(exc, context):
  # Call DRF's default exception handler first,
  # to get the standard error response.
  response = exception_handler(exc, context)

  # check that a ValidationError exception is raised
  if isinstance(exc, ValidationError): 
    # This is where you would prepare the 'custom_error_response'
    # and set the custom response data on response object
    response.data = custom_error_response 

  return response

要启用您的自定义处理程序,请在您的设置文件中添加 EXCEPTION_HANDLER 设置:

REST_FRAMEWORK = {
'PAGE_SIZE': 20,
'EXCEPTION_HANDLER': 'path.to.your.module.base_exception_handler',

'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication'
)

}

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 2016-11-06
    • 2016-05-03
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多