丛FBC到CBV三(权限)
<style></style> <style></style>权限
准备数据表
用户组(group) | |
id | group_name |
1 | usual |
2 | vip |
3 | svip |
4 | admin |
用户(user) | |||
id | username | password | group_id |
1 | Joshua | 123 | 1 |
2 | William | 123 | 2 |
3 | Daniel | 123 | 3 |
4 | Michael | 123 | 4 |
创建项目及app:
models.py <wiz_code_mirror> 19 19 1
# -*- coding:utf-8 -*-2
from django.db import models3 4
class Group(models.Model):5
id = models.AutoField(primary_key=True)6
group_name = models.CharField(max_length=40)7 8
class Meta:9
db_table = 'group'10 11
class User(models.Model):12
id = models.AutoField(primary_key=True)13
username = models.CharField(max_length=40,unique=True)14
password = models.CharField(max_length=40)15
group_id = models.ForeignKey(Group, default=1)16 17
class Meta:18
db_table = 'user'19 views.py <wiz_code_mirror> 16 16 1
from django.http.response import JsonResponse2
from rest_framework.views import APIView3 4
from permissions.models import User, Group5 6 7
class Users(APIView):8
def get(self, request):9
users = User.objects.all().values()10
return JsonResponse(list(users), safe=False)11 12 13
class Groups(APIView):14
def get(self, request):15
groups = Group.objects.all().values()16
return JsonResponse(list(groups), safe=False)urls.py <wiz_code_mirror> 9 9 1
from django.conf.urls import url2
from django.contrib import admin3
from permissions.views import Users, Groups4 5
urlpatterns = [6
url(r'^admin/', admin.site.urls),7
url(r'^user/$', Users.as_view(), name='user'),8
url(r'^group/$', Groups.as_view(), name='group'),9
]Postman提交请求:
现在新建了一张MemberPrograms表,里面的内容是只给会员用户展示的 实现这个功能:
会员项目(member_programs) | |
id | program_name |
1 | 书法长卷 |
2 | 书法碑帖 |
3 | 墓志塔铭 |
4 | 兰亭集序 |
class MemberProgram(models.Model):2
id = models.AutoField(primary_key=True)3
program_name = models.CharField(max_length=100)4 5
class Meta:6
db_table = 'member_program'定义url以及视图函数: <wiz_code_mirror> 9 9 1
from django.conf.urls import url2 3
from permissions.views import Users, Groups, MemberPrograms4 5
urlpatterns = [6
url(r'^user/$', Users.as_view(), name='user'),7
url(r'^group/$', Groups.as_view(), name='group'),8
url(r'^program/$', MemberPrograms.as_view(), name='program'),9
]<wiz_code_mirror> 4 4 1
class MemberPrograms(APIView):2
def get(self, request):3
programs = MemberProgram.objects.all().values()4
return JsonResponse(list(programs), safe=False)测试:
现在接口已经实现了,但是我们要对这个接口增加权限控制,只允许vip,svip,admin用户访问,代码实现: 方法一: 上一章我们实现了自定义认证的中间件,现在可以利用起来,修改如下: <wiz_code_mirror> 1 25 1
class MyAuthentication(BaseAuthentication):2
def authenticate(self, request):3
name = request._request.GET.get('username')4
print(name)5
return (name, None)6 7 8
class MemberPrograms(APIView):9
authentication_classes = [MyAuthentication, ]10 11
def get(self, request):12
if not request.user: # 没用用户身份,不允许访问13
ret = {'code': 1002, 'error': '权限被拒'}14
return JsonResponse(ret)15
username = request.user16
try:17
group_name = User.objects.get(username=username).group.group_name18
except User.DoesNotExist: # 用户身份不存在,返回错误信息19
ret = {'code': 1003, 'error': '用户不存在'}20
return JsonResponse(ret)21
if group_name == 'usual': # 是普通用户,没有权限22
ret = {'code': 1002, 'error': '权限被拒'}23
return JsonResponse(ret)24
programs = MemberProgram.objects.all().values() # 用户权限满足条件 返回接口信息25
return JsonResponse(list(programs), safe=False)测试:
上面实现了接口对用户权限的控制,实际项目代码不会这么简单,需要通过token进行判断,这里只是简单实现 方法二: 利用restframework的permission组件实现: <wiz_code_mirror>
x1
from rest_framework.authentication import BaseAuthentication2
from rest_framework.permissions import BasePermission3
from rest_framework.exceptions import PermissionDenied4 5
lass MyAuthentication(BaseAuthentication):6
def authenticate(self, request):7
name = request._request.GET.get('username')8
print(name)9
return (name, None)10 11 12
class MyPermission(BasePermission):13
def has_permission(self, request, view):14
if not request.user:15
raise PermissionDenied('权限被拒')16
username = request.user17
try:18
group_name = User.objects.get(username=username).group.group_name19
except User.DoesNotExist:20
raise PermissionDenied('用户不存在')21
if group_name == 'usual':22
raise PermissionDenied('权限被拒')23
return True24 25 26
class MemberPrograms(APIView):27
authentication_classes = [MyAuthentication, ]28
permission_classes = [MyPermission, ]29 30
def get(self, request):31
programs = MemberProgram.objects.all().values()32
return JsonResponse(list(programs), safe=False)上面的例子中我们都是将认证类和权限类注册在了对应的view视图中, 其实要是项目中多数视图需要进行以上验证,那就可将自定义的认证类和权限类放在一个单独的文件中,然后注册到seeting.py中 :
在seeting.py中添加下面内容: