如何在 Django 中使用 process_view() 创建基于函数的中间件?

我正在使用标准实现来实现新的中间件:


def my_middleware(get_response):

    def middleware(request):

        return get_response(request)

    return middleware

我想得到view_args. 我可以改为基于类的中间件并实现该方法


process_view(request, view_func, view_args, view_kwargs)


有没有其他方法可以在我的中间件中获取这些 view_args、view_kwargs 而无需更改为基于类的中间件?


三国纷争
浏览 134回答 2
2回答

DIEA

设置为函数process_view(...)的属性 为middleware(...)def process_view(request, view_func, view_args, view_kwargs):    """    do something    """def simple_middleware(get_response):    # One-time configuration and initialization.    def middleware(request):        # Code to be executed for each request before        # the view (and later middleware) are called.        response = get_response(request)        # Code to be executed for each request/response after        # the view is called.        return response    middleware.process_view = process_view    return middleware

catspeake

* process_view()应该返回None一个HttpResponse对象,否则会出现错误。该函数具有process_view():def process_view(request, view_func, view_args, view_kwargs):    # Do somethingdef simple_middleware(get_response):    # One-time configuration and initialization.    def middleware(request):        # Code to be executed for each request before        # the view (and later middleware) are called.        response = get_response(request)        # Code to be executed for each request/response after        # the view is called.        return response    middleware.process_view = process_view # Here    return middleware班级有process_view():class SimpleMiddleware:    def __init__(self, get_response):        self.get_response = get_response        # One-time configuration and initialization.    def __call__(self, request):        # Code to be executed for each request before        # the view (and later middleware) are called.        response = self.get_response(request)        # Code to be executed for each request/response after        # the view is called.        return response    def process_view(self, request, view_func, view_args, view_kwargs):        # Do something
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python