Make django middleware variables able to handle concurrent requests

I have to implement a custom middleware in django to count the number of requests served so far. It is a part of an assignment that I've got.

I have created the middleware like this

# myapp/middleware.py

from django.utils.deprecation import MiddlewareMixin

class RequestCounterMiddleware(MiddlewareMixin):
    request_count = 0

    def process_request(self, request):
        RequestCounterMiddleware.request_count += 1

    def process_response(self, request, response):
        return response

    @staticmethod
    def get_request_count():
        return RequestCounterMiddleware.request_count

Now my question is how to make the variable request_count able to handle concurrent requests and show the correct value.

ChatGPT suggested using threading.Lock(). Would that be a good option? If not, please suggest some other way. Thanks :)

Back to Top