Python Django DRF get request query param在自定义装饰器中应用于ViewSet.ViewSet中的函数
在django rest framework中,当创建自定义ViewSet.ViewSet时,我们可以对该ViewSet中的特定函数应用自定义装饰器吗Python Django DRF get request query param在自定义装饰器中应用于ViewSet.ViewSet中的函数,python,django,django-rest-framework,Python,Django,Django Rest Framework,在django rest framework中,当创建自定义ViewSet.ViewSet时,我们可以对该ViewSet中的特定函数应用自定义装饰器吗 class UserViewSet(viewsets.ViewSet): """ Example empty viewset demonstrating the standard actions that will be handled by a router class. If y
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操作上应用多个decorator
现在,我正试图这样做:
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”对象没有属性“query\u params”
Django提供了一种在基于类的视图上使用装饰器的简单方法(这也适用于DRF): 来自django.utils.decorators的
导入方法\u decorator
@方法_decorator(需要登录)#用您自己的decorator替换需要登录
def列表(自我、请求):
通过
更多信息:
但在您的情况下,我宁愿选择DRF自己的权限系统():
来自rest\u框架的导入权限
类CustomerAccessPermission(permissions.BasePermission):
def具有_权限(自我、请求、查看):
返回请求。query_params['role']==“admin”#或其他任何参数,只要它是布尔值
您似乎走在了正确的轨道上-请注意,您正在装饰一个方法,因此包装函数将viewset的self
作为第一个参数。您应该调整wrapper
签名,并返回view\u func(self,…)
,也就是说,当您在装饰器中检查与身份验证相关的内容时,最好使用自定义权限类来解决此问题。@mikerool我可以找到添加多个自定义权限示例的任何引用classes@PritamKadam