Python 试图从中间件功能中找出如何使用decorator\u
正如标题所述,我想在这里使用“decorator\u from\u middleware”函数: 然而,我只是对如何正确使用它感到困惑。我有我的自定义中间件类和所有正常的中间件设置。在装饰师的帮助下,我将如何使用这个函数来使用我的中间件作为每个视图的基础 例如: 假设我有一些中间件类Python 试图从中间件功能中找出如何使用decorator\u,python,django,decorator,middleware,Python,Django,Decorator,Middleware,正如标题所述,我想在这里使用“decorator\u from\u middleware”函数: 然而,我只是对如何正确使用它感到困惑。我有我的自定义中间件类和所有正常的中间件设置。在装饰师的帮助下,我将如何使用这个函数来使用我的中间件作为每个视图的基础 例如: 假设我有一些中间件类 class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response
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
如何使用中间件(中间件类)中的装饰器?并将其应用于特定视图?注意:您的中间件可能无法工作,因为文档断言它需要与旧式中间件方法兼容 假设此代码是您的视图模块:
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")
若要将此应用于基于类的视图,则需要修饰分派方法。您甚至可以这样编写一个mixin:
class SimpleMiddlewareMixin:
@simple_decorator
def dispatch(*args, **kwargs):
return super().dispatch(*args, **kwargs)
class MyClassBasedView(SimpleMiddlewareMixin, ListView):
...
非常感谢你!我会试试的这不行!