django-rest-framework - ViewSet 仅在一个 REST 操作(Django Rest)中使用令牌身份验证
问题描述
问题
我正在使用 Django 休息框架。在那种情况下,一个ViewSet
. 仅在我想使用的一项 REST 操作上Token Authentication
。DRF是否提供甚至提供类似的东西?
感谢您的帮助。
class UserProfileViewSet(viewsets.ModelViewSet):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
#Here the Token Authentication should be
def destroy(self, request, pk=None, **kwargs):
try:
user = User.objects.get(pk=pk)
user.delete()
except User.DoesNotExist:
return Response(status=status.HTTP_400_BAD_REQUEST)
return Response(status=status.HTTP_204_NO_CONTENT)
解决方案
覆盖该get_authenticators()
方法如下。该get_authenticators()
方法实例化并返回此视图可以使用的身份验证器列表。在您的情况下,该方法将返回/验证TokenAuthentication
如果操作是破坏,(HTTP DELETE
)
from rest_framework.authentication import TokenAuthentication
class UserProfileViewSet(viewsets.ModelViewSet):
# your code
authentication_classes = (TokenAuthentication,)
def get_authenticators(self):
if self.action == 'destroy':
return super().get_authenticators()
return []
def destroy(self, request, pk=None, **kwargs):
# your code
推荐阅读
- python - 事务请求不能包含对一项python的多个操作
- c++ - 如何在基于 Qt qmake 的项目中使用 CuteLogger?
- flutter - 如何禁用按钮(图标按钮)点击?
- c++ - 渲染边缘上的 CGAL::Triangulation_3 毛刺
- r - R中的sqldf比较两个data.frames并存储输出
- codesys - Codesys LD:如何从一个进程跳转到另一个进程
- python - 尝试查找并单击时出现 Selenium TimeoutException
- java - 在android应用程序中集成gmail登录的问题?
- python - 如何创建一个从元组列表中获取随机元组并在 python 中生成基本图的程序?
- linux - 在新版本中使用 docker rootless