4

How would one create "new style" middleware, which fulfills an equivalent implementation to using the process_request() hook with the "old style"?

I've already adapted pre 1.10 middleware process_request() using MiddlewareMixin...

from django.utils.deprecation import MiddlewareMixin

class MyCustomMiddleware(MiddlewareMixin):

    def process_request(self, request):
        # My request logic
        return response

I'd like to know how to do a "pure" >1.9 "new style" implementation. I tried doing so by implementing __init__() and __call__() like this without luck:

class MyCustomMiddleware(object):

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

    def __call__(self, request):
        # My request logic
        return response

Thanks.

conner.xyz
  • 6,273
  • 8
  • 39
  • 65

1 Answers1

13

Here an example...

class TimeStampMiddleware(object):

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

    def __call__(self, request):
        request.timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')

        response = self.get_response(request)
        return response

Now you can get the timestamp in every request from yours views! (is only an example)

ignabe
  • 2,310
  • 1
  • 15
  • 24
  • `process_request` was supposed to be called even for unknown views, with this new style of middleware it looks to be called just as "emulation layer" only for known views - so I cannot process requests that do not map to any view :( – Dmitriy Sintsov Oct 27 '17 at 09:40