django - Rest Framework 视图之外的 Django Rest Framework 权限
问题描述
我正在使用 Rest Framework 令牌身份验证。这意味着我无法知道用户是否在休息框架视图之外进行了身份验证,例如:(常规 django 视图)。Rest Framework 令牌身份验证是一个自定义身份验证系统,只能在 Rest Framework 视图中使用。
在正常的休息框架视图中,我可以使用以下方法限制经过身份验证的用户的端点:
class ExampleView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
但是对于常规的 django 视图,我将如何做到这一点。例如:
def someDjangoView(request):
'''
Note that I cannout use request.user.is_authenticated.
It will always return false as I am using rest framework token authentication.
Which means the request parameter should be of rest framework's and not django's built-in.
'''
content = {"detail": "Only authenticated users should access this"}
return JsonResponse(content)
我陷入了一种情况,我必须知道用户是否在休息框架视图之外进行了身份验证(自定义身份验证)。
有没有办法做到这一点?
解决方案
您可以在api_view
基于函数的视图中使用装饰器来启用 DRF:
from rest_framework.decorators import api_view, authentication_classes
@api_view(http_method_names=['GET', 'POST'])
@authentication_classes([YourTokenAuthenticationClass])
def someDjangoView(request):
print(request.user)
...
return JsonResponse(content)
推荐阅读
- testlink - 如何在 Testlink 上允许对已执行的测试用例进行需求版本链接管理
- flutter - 在 Flutter 中获取 Future var 的长度
- go - Textile Go - 通过 HTTP API 将文件添加到线程的描述不明确
- android - 使用 ConstraintLayout 中的圆形定位时如何设置按钮边距?
- python - 如何从熊猫数据框中的列中删除不必要的信息
- ios - Apple Seach Ads Discovery Campaigns 卡在等待受众规模验证
- c# - 在 C# 中创建对象和对象序列化
- asp.net - 如何从 Arraylist 中命名 JSON 数组
- arrays - Mongoose find method does not return array
- json - 有没有办法比较具有不同结构的两个属性文件的键?