为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

三国纷争 2023-08-15 17:30:50
我正在使用标准实现来实现新的中间件: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 而无需更改为基于类的中间件?
查看完整描述

2 回答

?
DIEA

TA贡献1820条经验 获得超2个赞

设置为函数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


查看完整回答
反对 回复 2023-08-15
?
catspeake

TA贡献1111条经验 获得超0个赞

* process_view()应该返回None一个HttpResponse对象,否则会出现错误。

该函数具有process_view()

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 # 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


查看完整回答
反对 回复 2023-08-15
  • 2 回答
  • 0 关注
  • 133 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信