简体   繁体   English

在 django 视图中定义装饰器的正确顺序是什么

[英]What is right order for defining decorators in django views

I want to set more than one decorator for my django function view.我想为我的 django function 视图设置多个装饰器。 The problem is that I can't figure out how should be the order of decorators.问题是我无法弄清楚装饰器的顺序应该如何。

For example this is the view I have:例如,这是我的观点:

@permission_classes([IsAuthenticated])
@api_view(["POST"])
def logout(request):
    pass

In this case, first decorator never applies!在这种情况下,第一个装饰器永远不会应用! neither when request is POST nor when it's GET!无论是 POST 请求还是 GET 请求!

When I change the order, to this:当我更改顺序时,为此:

@api_view(["POST"])
@permission_classes([IsAuthenticated])
def logout(request):
    pass

the last decorator applies before the first one, which is not the order that I want.最后一个装饰器在第一个装饰器之前应用,这不是我想要的顺序。

I want the decorator @api_view(["POST"]) to be applied first, and then @permission_classes([IsAuthenticated]) .我希望首先应用装饰器@api_view(["POST"]) ,然后应用@permission_classes([IsAuthenticated])

How should I do that?我该怎么做?

This is the correct way of ordering 'api_view' consider the view as API view that the decorator is defined by restframework.这是订购“api_view”的正确方式,将视图视为 API 视图,装饰器由 restframework 定义。

from rest_framework.decorators import api_view, permission_classes

@api_view(["POST"])
@permission_classes([IsAuthenticated])
def logout(request):
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM