
models.py
from django.db import models class UserInfo(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
role_choice = ((1,'管理员'),(2,'普通用户'))
role = models.IntegerField(choices=role_choice) class BWH(models.Model):
'''三围信息'''
bust = models.IntegerField(verbose_name='胸围')
waist = models.IntegerField(verbose_name='腰围')
hips = models.IntegerField(verbose_name='臀围') user = models.OneToOneField(to=UserInfo)
serializers.py
from rest_framework import serializers
from app01 import models class BWHModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.BWH
fields = '__all__' class UserModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = '__all__'
permission.py
from rest_framework.permissions import BasePermission
from app01 import models class AdminPermission(BasePermission):
'''管理员权限认证'''
message = '您没有权限访问!'
def has_permission(self, request, view):
user_id = request.GET.get('uid')
user = models.UserInfo.objects.filter(pk=user_id).first() if not user or user.role == 2:
return False
else:
return True
auth.py
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from app01 import models class BlackNameAuth(BaseAuthentication):
'''黑名单认证''' def authenticate(self, request):
BLACK_NAME_LIST = ['小花', '小翠'] # 通过从url获取user_id的方式模拟用户登录
user_id = request.GET.get('uid')
user = models.UserInfo.objects.filter(pk=user_id).first() if not user or user.username in BLACK_NAME_LIST:
raise AuthenticationFailed('您没有登录或者被关小黑屋啦')
else:
return user.username,user_id
urls.py
from django.conf.urls import url,include
from django.contrib import admin
from rest_framework import routers
from app01 import views # 实例化一个routers对象
routers = routers.DefaultRouter()
# 往对象里注册(添加)url
routers.register('bwh',views.BWHViewSet)
routers.register('user',views.UserViewSet) urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include(routers.urls))
]
view.py
from app01.serializers import BWHModelSerializer
from app01.serializers import UserModelSerializer
from rest_framework.viewsets import ModelViewSet
from app01 import models
from app01.auth import BlackNameAuth
from app01.permission import AdminPermission
from rest_framework.pagination import PageNumberPagination class MyPagination(PageNumberPagination):
'''分页,自定义每页显示2条'''
page_size = 2 class BWHViewSet(ModelViewSet):
'''在黑名单中的用户禁止查看三围信息'''
authentication_classes = [BlackNameAuth] # 分页
pagination_class = MyPagination serializer_class = BWHModelSerializer
queryset = models.BWH.objects.all() class UserViewSet(ModelViewSet):
'''非管理员禁止查看用户信息'''
permission_classes = [AdminPermission] # 分页
pagination_class = MyPagination serializer_class = UserModelSerializer
queryset = models.UserInfo.objects.all()