save Django2.2 404 request in database using middelware

86 Views Asked by At

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.

2

There are 2 best solutions below

0
Sifb71 On BEST ANSWER

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!

0
willeM_ Van Onsem On

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