簡體   English   中英

Django DRF 獲取自定義裝飾器中的請求查詢參數,應用於viewsets.ViewSet中的function

[英]Django DRF get request query param in custom decorator applied on a function in viewsets.ViewSet

在 django rest 框架中創建自定義視圖集時,我們可以在該視圖集中的特定 function 上應用自定義裝飾器嗎?

class UserViewSet(viewsets.ViewSet):
    """
    Example empty viewset demonstrating the standard
    actions that will be handled by a router class.

    If you're using format suffixes, make sure to also include
    the `format=None` keyword argument for each action.
    """

    @permission_classes([IsAuthenticated])
    @custom_decorator_1()
    def list(self, request):
        pass

    @custom_decorator_2()
    def create(self, request):
        pass

    @custom_decorator_3()
    def retrieve(self, request, pk=None):
        pass

    def update(self, request, pk=None):
        pass

    def partial_update(self, request, pk=None):
        pass

    def destroy(self, request, pk=None):
        pass

如果是,那么我們如何在 ViewSet 上應用的自定義裝飾器中獲取查詢參數? 或者是否有任何替代解決方案可以實現這一點,我可以在 ViewSet 操作上應用多個裝飾器?

現在我正在嘗試以這種方式做到這一點:

def custom_decorator():
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """

    def decorator(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):

            role = request.query_params['role']
            
            return view_func(request, *args, **kwargs)

        return wrapper

    return decorator

收到錯誤:

AttributeError: 'UserViewSet' object 沒有屬性 'query_params'

Django 提供了一種在基於 class 的視圖上使用裝飾器的簡單方法(這也適用於 DRF):

from django.utils.decorators import method_decorator

@method_decorator(login_required) #replace login_required with your own decorator
    def list(self, request):
        pass

更多信息: https://docs.djangoproject.com/en/3.1/topics/class-based-views/intro/#decorating-the-class

但在你的情況下,我寧願 go 用於 DRF 自己的權限系統( https://www.django-rest-framework.org/api-guide/permissions/

from rest_framework import permissions

class CustomerAccessPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.query_params['role'] == "admin" #or whatever as long as it is a boolean

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM