django - 对通用 API 视图的特定方法进行身份验证
问题描述
我已经使用ListCreateAPIView
和RetrieveUpdateDestroyAPIView
作为模型。现在我想将JWT身份验证添加到RetrieveUpdateDestroyAPIView
. 我怎样才能做到这一点?
让我把我的问题说得更清楚一点。我有一个名为Post
. 现在所有用户都可以查看帖子,但更新、删除仅对创建它的用户可用。我想使用JWT Authentication。
解决方案
您可以为此编写自定义权限类:
from rest_framework import permissions
class CustomPermission(permissions.BasePermission):
def has_permission(self, request, view):
if view.action in ('update', 'destroy'):
return request.user.is_authenticated
return True
并在您的视图中使用:
class ExampleView(RetrieveUpdateDestroyAPIView):
permission_classes = (CustomPermission,)
推荐阅读
- python - 从列表中获取相对于python中另一个元素的元素
- c# - Podio AuthenticateWithApp 在 Windows Server 2008 上引发 WinHttpException
- php - PHP获取当前日期时间+一年(也询问是否安全)
- javascript - Laravel:我在使用 Ajax 发布数据时遇到了一些问题
- systemd - 如何在依赖更新时通知 apt/dpkg 依赖包?
- python - 有没有办法以编程方式知道 Python 函数何时完成处理?
- android - 启动画面上的致命错误,它突然停止应用程序
- python - 无法从 Python 请求中检索响应数据
- node.js - winston - TypeError:winston.createLogger 不是构造函数
- node.js - Mongo聚合多个排序阶段(nodejs)