Django 1.10: “new style” middleware equivalent of `process_request()`

折月煮酒 提交于 2019-12-10 15:25:58

问题


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.


回答1:


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)



来源:https://stackoverflow.com/questions/40876355/django-1-10-new-style-middleware-equivalent-of-process-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!