当前位置:   article > 正文

Django restframework permission 权限_"rest_framework.permissions\" does not define a \"

"rest_framework.permissions\" does not define a \"isauthenticaticated"

权限一般与认证放到一起,权限检查一般是检查 request.user 和 request.auth属性中的身份验证信息来确定是否允许传入请求。权限用于授予或拒绝不同类别的用户对不同API的访问。最简单的权限是允许所有经过身份认证的用户,这对应着IsAuthenticated类。

如何确定权限

REST框架中的权限和认证一样:为权限类列表。

在运行视图主体之前,将检查列表中的每个权限。如果任何权限检查失败,则将引发exceptions.PermissionDeniedexceptions.NotAuthenticated异常,并且视图主体将不运行。

if request.method in permissions.SAFE_METHODS: # read-only
            return True

设置权限策略:第一个样例

可以使用该DEFAULT_PERMISSION_CLASSES设置在全局范围内设置默认权限策略。例如。

  1. REST_FRAMEWORK = {
  2. 'DEFAULT_PERMISSION_CLASSES': [
  3. 'rest_framework.permissions.IsAuthenticated',
  4. ]
  5. }

如果未指定,则此设置默认为允许无限制访问:

  1. 'DEFAULT_PERMISSION_CLASSES': [
  2. 'rest_framework.permissions.AllowAny',
  3. ]

您还可以使用APIView基于类的视图基于每个视图或每个视图集设置身份验证策略。

  1. from rest_framework.permissions import IsAuthenticated
  2. from rest_framework.response import Response
  3. from rest_framework.views import APIView
  4. class ExampleView(APIView):
  5. permission_classes = [IsAuthenticated]
  6. def get(self, request, format=None):
  7. content = {
  8. 'status': 'request was permitted'
  9. }
  10. return Response(content)

 自定义权限:第二个样例

step1:APP目录下生成utils目录,utils目录下生成permission.py文件,并编写认证类代码:

To implement a custom permission, override BasePermission and implement either, or both, of the following methods:

  • .has_permission(self, request, view)
  • .has_object_permission(self, request, view, obj)

The methods should return True if the request should be granted access, and False otherwise.

If you need to test if a request is a read operation or a write operation, you should check the request method against the constant SAFE_METHODS, which is a tuple containing 'GET''OPTIONS' and 'HEAD'. For example:

  1. if request.method in permissions.SAFE_METHODS:
  2. # Check permissions for read-only request
  3. else:
  4. # Check permissions for write request
  1. from rest_framework.permissions import BasePermission
  2. class SVIPPremission(BasePermission):
  3. message = "必须是SVIP才能访问"
  4. def has_permission(self,request,view):
  5. if request.user.user_type != 3:
  6. return False
  7. return True

step2:DEFAULT_AUTHENTICATION_CLASSES设置全局设置默认身份验证方案,例如:

  1. REST_FRAMEWORK = {
  2. 'DEFAULT_AUTHENTICATION_CLASSES': [
  3. 'rest_framework.authentication.BasicAuthentication',
  4. 'rest_framework.authentication.SessionAuthentication',
  5. 'pert.utils.authenticate.FirstAuthenticate',
  6. 'pert.utils.authenticate.MyAuthenticate',
  7. ],
  8. "DEFAULT_PERMISSION_CLASSES": ['pert.utils.permission.MyPermission'],
  9. }

step3:在Views文件中使用身份验证方案(并编号URL文件)

  1. #urls.py
  2. from django.contrib import admin
  3. from django.urls import path
  4. from django.conf.urls import url
  5. from pert.views import AuthView
  6. from pert.views import OrderView
  7. from pert.views import UserInfoView
  8. from pert.views import Example
  9. urlpatterns = [
  10. path('admin/', admin.site.urls),
  11. path('example', Example.as_view()),
  12. path('api/v1/auth/', AuthView.as_view()),
  13. path('api/v1/order/', OrderView.as_view()),
  14. path('api/v1/info/', UserInfoView.as_view())
  15. ]
  16. #views.py
  17. from django.shortcuts import render, HttpResponse
  18. from django.http import JsonResponse
  19. from django.views import View
  20. from rest_framework import exceptions
  21. from rest_framework.views import APIView
  22. from rest_framework.parsers import JSONParser
  23. from rest_framework.authentication import BaseAuthentication, SessionAuthentication, BasicAuthentication
  24. from rest_framework.permissions import IsAuthenticated
  25. from rest_framework.response import Response
  26. from pert import models
  27. import json
  28. ORDER_DICT = {
  29. 1:{
  30. 'name':'apple',
  31. 'price':15
  32. },
  33. 2:{
  34. 'name':'dog',
  35. 'price':100
  36. }
  37. }
  38. def md5(user):
  39. import hashlib
  40. import time
  41. # 当前时间,相当于生成一个随机的字符串
  42. ctime = str(time.time())
  43. # token加密
  44. m = hashlib.md5(bytes(user, encoding='utf-8'))
  45. m.update(bytes(ctime, encoding='utf-8'))
  46. return m.hexdigest()
  47. class AuthView(View):
  48. authentication_classes = []
  49. permission_classes = []
  50. def get(self, request, *args, **kwargs):
  51. ret = {'code': 1000, 'msg': 'success', 'name': 'get method'}
  52. ret = json.dumps(ret, ensure_ascii=False)
  53. return HttpResponse(ret)
  54. def post(self, request, *args, **kwargs):
  55. ret = {'code': 1000, 'msg': None}
  56. try:
  57. data = JSONParser().parse(request)
  58. user = data["username"]
  59. pwd = data["password"]
  60. # user = request.data.get("username")
  61. # pwd = request.data.get("password")
  62. obj = models.UserInfo.objects.filter(username=user).first()
  63. if not obj:
  64. obj = models.UserInfo.objects.create(username=user, password=pwd)
  65. ret['code'] = 1001
  66. ret['msg'] = '创建用户成功'
  67. # 为用户创建token
  68. token = md5(user)
  69. # 存在就更新,不存在就创建
  70. models.UserToken.objects.update_or_create(user=obj, defaults={'token': token})
  71. ret['token'] = token
  72. except Exception as e:
  73. ret['code'] = 1002
  74. ret['msg'] = '请求异常'
  75. return JsonResponse(ret)
  76. import pert.utils.authenticate as authenticate
  77. import pert.utils.permission as permission
  78. class OrderView(APIView):
  79. permission_classes = []
  80. def get(self, request, *args, **kwargs):
  81. print(str(request.user))
  82. ret = {
  83. 'code': 1024,
  84. 'msg': '订单获取成功',
  85. }
  86. try:
  87. ret['data'] = ORDER_DICT
  88. except Exception as e:
  89. pass
  90. return JsonResponse(ret)
  91. class UserInfoView(APIView):
  92. def get(self, request, *args, **kwargs):
  93. print(request.user)
  94. return HttpResponse('SVIP用户信息')

step4:验证(修改数据库usertype)

最后permission权限是根据认证返回的user 和auth进行权限的判断的,需要注意

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/71652
推荐阅读
相关标签
  

闽ICP备14008679号