0

i write a custom middilware to save all request in my database. this is my code:

class TestMiddleware(MiddlewareMixin):
      def process_response(self, request, response):
           ....
           # save my request attr in database
           HttpRequestLog.objects.create(**params)
           ...

     def process_exception(self, request, exception):
           ....
           # save my request attr in database
           HttpRequestLog.objects.create(**params)
           ...

i have a problem. when user call a wrong url apis , Django return 404 status but this code save nothing to my database and i have n't any error!!!

               HttpRequestLog.objects.create(**params)

my code is worked when api returned 200 or 204 or 201 status.

Sifb71
  • 41
  • 10

2 Answers2

0

A 404 is often done by an exception, not a HTTP response. It is then the Django framework that converts this exception into a HTTP 404 response.

You thus can "catch" the error, log the response, and reraise it:

class TestMiddleware(MiddlewareMixin):
    
    def process_response(self, request, response):
        …
        # save my request attr in database
        HttpRequestLog.objects.create(**params)

    def process_exception(self, request, exception):
        if isinstance(exception, Http404):
            # …
        return None
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

I finally found the solution to the problem!

I use a revision middleware in my code and I change my middleware sort and place my middleware above revision middleware and every thing is successfully worked!

Sifb71
  • 41
  • 10