权限:判断用户有哪些访问数据的权限
-
由于认证已经完成,request内就有了user对象,当前的登陆用户
models.py
from django.db import models
# Create your models here.
from django.db import models
# Create your models here.
class Book(models.Model):
name=models.CharField(max_length=32)
price=models.DecimalField(max_digits=5,decimal_places=2)
publish=models.CharField(max_length=32)
class User(models.Model):
username=models.CharField(max_length=32)
password=models.CharField(max_length=32)
user_type=models.IntegerField(choices=((1,'超级用户'),(2,'普通用户'),(3,'二笔用户')))
class UserToken(models.Model):
token=models.CharField(max_length=64)
user=models.OneToOneField(to=User,on_delete=models.CASCADE) #一对一关联到User表
- ser.py
from rest_framework import serializers
from app01.models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model=Book
fields='__all__'
- views.py
from django.shortcuts import render
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
import uuid
from rest_framework.request import Request
from app01 import models
class LoginView(APIView):
authentication_classes = []
def post(self,request):
username=request.data.get('username')
password=request.data.get('password')
user=models.User.objects.filter(username=username,password=password).first()
if user:
# 登陆成功,生成一个随机字符串
token=uuid.uuid4()
# 存到UserToken表中
# models.UserToken.objects.create(token=token,user=user)# 用它每次登陆都会记录一条,不好,如有有记录
# update_or_create有就更新,没有就新增
models.UserToken.objects.update_or_create(defaults={'token':token},user=user)
return Response({'status':100,'msg':'登陆成功','token':token})
else:
return Response({'status': 101, 'msg': '用户名或密码错误'})
from app01 import app_auth
# 这个只有超级用户可以访问
class TestView(APIView):
authentication_classes = [app_auth.MyAuthentication]
permission_classes = [app_auth.UserPermission]
def get(self,request,*args,**kwargs):
return Response('这是测试数据')
# 只要登录用户就可以访问
class TestView2(APIView):
authentication_classes = [app_auth.MyAuthentication]
def get(self,request,*args,**kwargs):
return Response('这是22222222测试数据')
# #演示内置权限,超级管理员可以查看
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication,BasicAuthentication
class TestView3(APIView):
authentication_classes=[SessionAuthentication,]
permission_classes = [IsAdminUser]
def get(self,request,*args,**kwargs):
return Response('这是22222222测试数据,超级管理员可以看')
##解析组件
from rest_framework.parsers import MultiPartParser #传文件的格式 formdata格式
## 频率限制
from rest_framework.throttling import BaseThrottle
# test4 演示全局未登录用户访问频次
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication,BasicAuthentication
class TestView4(APIView):
authentication_classes=[]
permission_classes = []
def get(self,request,*args,**kwargs):
return Response('我是未登录用户')
# test5 演示局部配置未登录用户访问频次
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication,BasicAuthentication
from rest_framework.throttling import AnonRateThrottle
from app01.app_auth import MyAuthentication
class TestView5(APIView):
# authentication_classes=[MyAuthentication]
permission_classes = []
throttle_classes = [AnonRateThrottle]
def get(self,request,*args,**kwargs):
# 1/0
return Response('我是未登录用户,TestView5')
# test6 演示登录用户每分钟访问10次,未登录用户访问5次
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.throttling import AnonRateThrottle
from rest_framework.viewsets import ModelViewSet
class TestView6(APIView):
authentication_classes = [SessionAuthentication]
def get(self, request, *args, **kwargs):
return Response('我是未登录用户,TestView6')
# 过滤组件的使用
from rest_framework.generics import GenericAPIView
from rest_framework.generics import ListAPIView
from app01.models import Book
from app01.ser import BookSerializer
class BookView(ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
filter_fields = ('name','price')
# 排序组件的使用
from rest_framework.generics import ListAPIView
from rest_framework.filters import OrderingFilter
from app01.models import Book
from app01.ser import BookSerializer
class Book2View(ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
filter_backends = [OrderingFilter]
ordering_fields = ('id', 'price')
#全局异常处理
from rest_framework.views import exception_handler
# 子定制返回对象
from app01.app_auth import APIResponse
class TestView7(APIView):
def get(self,request,*args,**kwargs):
return APIResponse(data={"name":'lqz'},token='dsafsdfa',aa='dsafdsafasfdee')
- app_auth.py
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from app01.models import UserToken
class MyAuthentication(BaseAuthentication):
def authenticate(self, request):
# 认证逻辑,如果认证通过,返回两个值
#如果认证失败,抛出AuthenticationFailed异常
token=request.GET.get('token')
if token:
user_token=UserToken.objects.filter(token=token).first()
# 认证通过
if user_token:
return user_token.user,token
else:
raise AuthenticationFailed('认证失败')
else:
raise AuthenticationFailed('请求地址中需要携带token')
from rest_framework.permissions import BasePermission
class UserPermission(BasePermission):
def has_permission(self, request, view):
# 不是超级用户,不能访问
# 由于认证已经过了,request内就有user对象了,当前登录用户
user=request.user # 当前登录用户
# 如果该字段用了choice,通过get_字段名_display()就能取出choice后面的中文
print(user.get_user_type_display())
if user.user_type==1:
return True
else:
return False
# 自定义异常处理的方法
from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
def my_exception_handler(exc, context):
response=exception_handler(exc, context)
# 两种情况,一个是None,drf没有处理
#response对象,django处理了,但是处理的不符合咱们的要求
# print(type(exc))
if not response:
if isinstance(exc, ZeroDivisionError):
return Response(data={'status': 777, 'msg': "除以0的错误" + str(exc)}, status=status.HTTP_400_BAD_REQUEST)
return Response(data={'status':999,'msg':str(exc)},status=status.HTTP_400_BAD_REQUEST)
else:
# return response
return Response(data={'status':888,'msg':response.data.get('detail')},status=status.HTTP_400_BAD_REQUEST)
#自己封装Response对象
from rest_framework.response import Response
# return APIResponse(100,'成功',data)
class APIResponse(Response):
def __init__(self,code=100,msg='成功',data=None,status=None,headers=None,**kwargs):
dic = {'code': code, 'msg': msg}
if data:
dic = {'code': code, 'msg': msg,'data':data}
dic.update(kwargs)
super().__init__(data=dic, status=status,headers=headers)
使用内置的权限及登录认证
权限必须和认证合起来用,不然报错
使用了默认的权限,就得使用默认的认证
-
自带的权限与认证
演示一下内置权限的使用:IsAdminUser,控制是否对网站后台有权限的人
1 创建超级管理员
命令行执行:createsuperuser
2 写一个测试视图类
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication
class TestView3(APIView):
authentication_classes=[SessionAuthentication,]
permission_classes = [IsAdminUser] 判断是否是超级管理员
def get(self,request,*args,**kwargs):
return Response('这是22222222测试数据,超级管理员可以看')
3 超级用户登录到admin,再访问test3就有权限
4 正常的话,普通管理员,没有权限看(判断的是is_staff字段)