当前位置:   article > 正文

python (django) 3. 权限 permission_detail": "you do not have permission to perform th

detail": "you do not have permission to perform this action.

1. api/permission.py

  1. # -*- coding: utf8 -*-
  2. class GradeOnePermission(object):
  3. def has_permission(self, request, view):
  4. grade = request.user.grade
  5. print(request.user)
  6. print(grade)
  7. if grade == 1:
  8. return True
  9. else:
  10. return False

2. api/views.py

  1. from api.authenticate import StudentAuthenticate
  2. from api.permission import GradeOnePermission
  3. class TokenView(GenericViewSet):
  4. # authentication_classes = []
  5. permission_classes = [GradeOnePermission]
  6. parser_classes = [JSONParser, ]
  7. def get(self, request, *args, **kwargs):
  8. name = request.query_params.get('name')
  9. try:
  10. stu = Student.objects.get(name=name)
  11. except Student.DoesNotExist:
  12. raise ParseError(_('Student does not include this name'))
  13. token = stu.token.token
  14. res = dict()
  15. res['code'] = 200
  16. res['name'] = name
  17. res['token'] = token
  18. logger.info(pformat(res))
  19. return Response(data=res, status=status.HTTP_200_OK)

3. settings.py

  1. REST_FRAMEWORK = {
  2. 'DEFAULT_AUTHENTICATION_CLASSES': ['api.authenticate.StudentAuthenticate'],
  3. 'DEFAULT_PERMISSOIN_CLASSES': ['api.permission.GradeOnePermisson'],
  4. }

4. postman

(1)

url: http://127.0.0.1:8011/api/v1/auth/

method: post

data: {
    "name": "student2",
    "password": "password1",
    "grade": 2
}

return:

{
    "code": 200,
    "name": "student2",
    "token": "950f0ed2b4f164900f996bf1c6bf225c",
    "msg": "创建成功"
}

(2)

url: http://127.0.0.1:8011/api/v1/token/?name=student2&token=950f0ed2b4f164900f996bf1c6bf225c

method: get

return:

{
    "detail": "You do not have permission to perform this action."
}

(3)

url: http://127.0.0.1:8011/api/v1/token/?name=student1&token=dbfa6b230b9ca22302a00ea918346f86

method: get

return:

{
    "code": 200,
    "name": "student1",
    "token": "dbfa6b230b9ca22302a00ea918346f86"
}

 

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

闽ICP备14008679号