赞
踩
1. api/permission.py
- # -*- coding: utf8 -*-
-
-
- class GradeOnePermission(object):
-
- def has_permission(self, request, view):
- grade = request.user.grade
- print(request.user)
- print(grade)
- if grade == 1:
- return True
- else:
- return False
2. api/views.py
- from api.authenticate import StudentAuthenticate
- from api.permission import GradeOnePermission
-
-
- class TokenView(GenericViewSet):
-
- # authentication_classes = []
- permission_classes = [GradeOnePermission]
- parser_classes = [JSONParser, ]
-
- def get(self, request, *args, **kwargs):
- name = request.query_params.get('name')
- try:
- stu = Student.objects.get(name=name)
- except Student.DoesNotExist:
- raise ParseError(_('Student does not include this name'))
-
- token = stu.token.token
- res = dict()
- res['code'] = 200
- res['name'] = name
- res['token'] = token
- logger.info(pformat(res))
-
- return Response(data=res, status=status.HTTP_200_OK)
3. settings.py
- REST_FRAMEWORK = {
- 'DEFAULT_AUTHENTICATION_CLASSES': ['api.authenticate.StudentAuthenticate'],
- 'DEFAULT_PERMISSOIN_CLASSES': ['api.permission.GradeOnePermisson'],
- }
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"
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。