1

我通过 DRF 获取nameage存储在数据库中,并创建检查错误和响应错误以及 status_code 的中间件,当中间件错误发生时,例如 404“找不到页面,无效 URL”等。我想将其存储'error and status_code'在数据库中。所以我怎么能通过它。

模型:

class Userdata(models.Model):
name = models.CharField(max_length=150)
age = models.IntegerField()

class Errorcode(models.Model):
status_code = models.CharField(max_length=150)
message = models.CharField(max_length=300)

意见:

class UserdataList(generics.ListCreateAPIView):
queryset = Userdata.objects.all()
serializer_class = UserdataSerializer

class UserdataDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Userdata
serializer_class = UserdataSerializer

class ErrorcodeList(generics.ListCreateAPIView):
queryset = Errorcode.objects.all()
serializer_class = ErrorcodeSerializer

class ErrorcodeDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Errorcode
serializer_class = ErrorcodeSerializer

中间件:

def get_response(message="", status_code=200):
return {
   "status_code" : status_code,
   "error" : message,
}

class ExceptionMiddleware(object):
def __init__(self, get_response):
   self.get_response = get_response

def __call__(self, request):

   response = self.get_response(request)

   if response.status_code == 500:
       response = get_response(
           message="Internal server error, please try again later",
           status_code=response.status_code
       )
       return JsonResponse(response, status=response['status_code'])

   if response.status_code == 404 and "Page not found" in str(response.content):
       response = get_response(
           message="Page not found, invalid url",
           status_code=response.status_code
       )
       return JsonResponse(response, status=response['status_code'])

   return response
4

0 回答 0