0 认证类的token从请求头中取
1 登录接口,编写图书的5个接口
-不登录就能查询所有图书
-查询单条,新增,修改,删除,都需要登录后才访问
-删除和修改要超级管理员才能操作
-所有接口,一秒钟只能访问2次
auth.py
from rest_framework.authentication import BaseAuthentication
from .models import UserToken
from rest_framework.exceptions import AuthenticationFailed
class LoginAuth(BaseAuthentication):
def authenticate(self, request): # 父类中有,一定要重写
# 校验用户是否登录---》请求中携带我给的token,就是登录了
# token在哪携带,是接口规定的---》
# 1 规定带在请求地址中---》讲这个
# 2 规定带在请求头中(这个多)
# 3 规定待在请求体中
# 取出token META HTTP_TOKEN
# # token=request.query_params.get('token')
token=request.META.get('HTTP_TOKEN')
# 去数据库中,根据token,校验有没有数据
usertoken_obj = UserToken.objects.filter(token=token).first()
if usertoken_obj:
user = usertoken_obj.user # 当前登录用户就是user
return user, token
# 检测失败,抛出异常
raise AuthenticationFailed('需要登录')
permission.py
from rest_framework.permissions import BasePermission
class AdminPermission(BasePermission):
def has_permission(self, request, view):
if request.user.auth==1:return 1
self.message='您好,%s,您无权操作'%resuest.user.name#request.message='没有权限'
return 0
throttling.py
from rest_framework.throttling import SimpleRateThrottle
class MyThrottle(SimpleRateThrottle):
scope = 'mmy'
def get_cache_key(self, request, view):
# 返回客户端ip地址:
ip=request.META.get('REMOTE_ADDR')
print('客户端的ip是:',ip)
return ip
settings.py加入以下代码
REST_FRAMEWORK= {
'DEFAULT_AUTHENTICATION_CLASSES': [
'app01.auth.LoginAuth',
],
'DEFAULT_PERMISSION_CLASSES': [
# 'app01.permission.AdminPermission'
],
'DEFAULT_THROTTLE_CLASSES': [
'app01.throttling.MyThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'mmy': '2/m'
},
}
views.py
from django.shortcuts import render
# Create your views here.
from . import models
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
import uuid
from rest_framework.decorators import action
from rest_framework.generics import ListCreateAPIView,RetrieveAPIView,RetrieveUpdateDestroyAPIView
from .serializer import BookSerializer
class UserView(ViewSet):
#局部禁用
authentication_classes = []
permission_classes = []
@action(methods=['POST'],detail=False)
def login(self,request):
user=request.data.get('user')
pwd=request.data.get('pwd')
print('user=',user,'pwd=',pwd)
userobj=models.User.objects.filter(name=user,pwd=pwd).first()
print(userobj)
if userobj:
token=str(uuid.uuid4())
print(token)
models.UserToken.objects.update_or_create(user=userobj,defaults={'token':token})
return Response({'code':100,'msg':'登录ok','token':token})
return Response({'code':101,'msg':'用户名密码错误'})
class BookView(GenericAPIView):
queryset = models.Book.objects.all()
serializer_class = BookSerializer
def get(self, request):
print(request.user.name, '访问了get接口')
qs=self.get_queryset().all()
ser=self.get_serializer(qs,many=True)
return Response({'data':ser.data})
def post(self, request):
print(request.user.name, '访问了post接口')
# qs=self.get_queryset().all()
ser=self.get_serializer(data=request.data)
if ser.is_valid():
ser.save()
return Response({'data':ser.data})
Response({'msg': ser.errors})
class BookRetrieveView(GenericAPIView):
queryset = models.Book.objects.all()
serializer_class = BookSerializer
def get(self, request,pk):
print(request.user.name, '访问了get,one接口')
qs=self.get_object()
print(qs)
print(11111111)
ser = self.get_serializer(qs)
return Response({'data': ser.data})
class BookDetailView(GenericAPIView):
from app01.permission import AdminPermission
permission_classes = [AdminPermission,]
queryset = models.Book.objects.all()
serializer_class = BookSerializer
def put(self, request,pk):
print(request.user.name, '访问了put接口')
qs=self.get_object()
ser=self.get_serializer(qs,data=request.data)
if ser.is_valid():
ser.save()
return Response({'data':ser.data})
Response({'msg': ser.errors})
def delete(self, request,pk):
print(request.user.name, '访问了del接口')
qs = self.get_object().delete()
-----一般人写不出来----
2 使用django中间件实现,按ip地址,一分钟只能访问5次的限制