【问题标题】:Trying to figure out how to use decorator_from_middleware functionality试图弄清楚如何使用 decorator_from_middleware 功能
【发布时间】:2020-05-21 16:21:27
【问题描述】:

正如标题所说,我想从这里使用“decorator_from_middleware”函数:https://docs.djangoproject.com/en/2.1/_modules/django/utils/decorators/

但是我只是对如何正确使用它感到困惑。我有我的自定义中间件类和所有正常的中间件设置。在装饰器的帮助下,我将如何合并此功能以便能够将我的中间件用作每个视图的基础?

示例: 假设我有一些中间件类

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

如何使用decorator_from_middleware(middleware_class): 并将其应用于特定视图?

【问题讨论】:

    标签: python django decorator middleware


    【解决方案1】:

    注意:您的中间件可能无法正常工作,因为文档声称它需要与旧式中间件方法兼容。 Check it out

    假设这段代码是你的视图模块:

    from django.http import HttpResponse
    from django.utils.decorators import decorator_from_middleware
    from myapp.middleware import SimpleMiddleware
    
    simple_decorator = decorator_from_middleware(SimpleMiddleware)
    
    @simple_decorator 
    def some_view(request):
        return HttpResponse("Hello World")
    

    如果你想把它应用到基于类的视图上,你需要装饰 dispatch 方法。你甚至可以这样写一个 mixin:

    class SimpleMiddlewareMixin:
        @simple_decorator 
        def dispatch(*args, **kwargs):
            return super().dispatch(*args, **kwargs)
    
    class MyClassBasedView(SimpleMiddlewareMixin, ListView):
        ...
    

    【讨论】:

    • 非常感谢!我一定会试试这个
    猜你喜欢
    • 2020-08-27
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 2016-03-11
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多