pythondjangosessionmiddlewarerequestcontext

Add metadata to WSGIRequest object


I have Django1.9 middleware class:

class MyMiddleware(object):

    def process_request(self, request):
        token = self._get_or_create_token(request)
        #request.context['token'] = token 

The issue is: - I would like to put token to some sort of context to pass it through the application flow. - I avoid putting it into request session, because it result in extra database reading/writing.

Could you suggest me some solution?


Solution

  • You can add any attribute to the HttpRequest, so you can implement this with:

    class MyMiddleware(object):
    
        def process_request(self, request):
            token = self._get_or_create_token(request)
            request.token = token

    or if you really want some sort of context dictionary:

    class MyMiddleware(object):
    
        def process_request(self, request):
            token = self._get_or_create_token(request)
            if not hasattr(request, 'context'):
                request.context = {}
            request.context['token'] = token

    I have Django1.9 middleware class.

    As is documented, is not supported anymore since April 2017, therefore I strongly advice to update.