reg: Django custom middleware

81 views
Skip to first unread message

Amitesh Sahay

unread,
Jan 24, 2024, 12:29:45 PM1/24/24
to Django Users, Django developers (Contributions to Django itself)
Hi All,

I have written a custom Django middleware to do retries and catch exception if there is any connection related issues between two servers. Below is the code snippet.

from requests.adapters import Retry, RetryError, HTTPAdapter, MaxRetryError, ConnectTimeoutError, ProtocolError, ResponseError
from requests.sessions import Session
from django.http import HttpResponseServerError


class RetryCal:
    def __init__(self, get_response):
        self.get_response = get_response

    @staticmethod
    def process_request(request):
        try:
            session = Session()
            retries = Retry(total=5, backoff_factor=2, status_forcelist=[500, 502, 503, 504])
            session.mount('https://', HTTPAdapter(max_retries=retries))
            request.retry_session = session

        except Exception as e:
            raise e

    def __call__(self, request):
        RetryCal.process_request(request)
        try:
            response = self.get_response(request)
            return response

        except (ProtocolError, OSError) as err:
            raise ConnectionError(err, request)

        except MaxRetryError as e:
            if isinstance(e.reson, ConnectTimeoutError):
                return HttpResponseServerError("Connection timeout error...")
            if isinstance(e.reson, ResponseError):
                raise RetryError(e, request=request)

            raise ConnectionError(e, request)


Below is the placement of the custom middleware

'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',

# custom retry middleware.
'integ.api_retry_custom_middleware.RetryCal',

below this custom middleware I do have other default one's as well.

The problem is I am not sure if this is working. I have an access token, In that I added some garbage characters and tried to hit my endpoint. I did see an exception as seen below

Internal Server Error: /api/acct/
[24/Jan/2024 14:23:39] "GET /api/acct/ HTTP/1.1" 500 5348

But I can see this error even if I comment out my custom middleware. My purpose is to create the custom middleware and if there is any API request from any Django App the request should go first through the custom middleware. That is my thought. But I am not sure if the middleware is working. Or maybe the placement if the custom middleware is not proper. I have been working with Django for a while now but written the custom middleware for the first time.

Please suggest.



Regards,
Amitesh

ASAMOAH EMMANUEL

unread,
Jan 24, 2024, 4:17:22 PM1/24/24
to django...@googlegroups.com
class RetryCal:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        try:
            session = Session()
            retries = Retry(total=5, backoff_factor=2, status_forcelist=[500, 502, 503, 504])
            session.mount('https://', HTTPAdapter(max_retries=retries))
            request.retry_session = session
        except Exception as e:
            raise e

        response = self.get_response(request)

        try:
            if isinstance(response, HttpResponseServerError):
                # Handle your custom response here if needed
                pass

        except (ProtocolError, OSError) as err:
            raise ConnectionError(err, request)

        return response

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/304829749.259529.1706099335383%40mail.yahoo.com.
Reply all
Reply to author
Forward
0 new messages