from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import BasePermission
from rest_framework.throttling import BaseThrottle,SimpleRateThrottle
from django_redis import get_redis_connection
from rest_framework import exceptions
import pickle
from app import models
class Myauthentication(BaseAuthentication):
def authenticate(self, request):
token=request.GET.get('token')
token=pickle.dumps(token)
conn=get_redis_connection()
conn_token=conn.get('token')
if token==conn_token:
user=models.User.objects.filter(id=pickle.loads(token)).first()
return user,token
raise exceptions.AuthenticationFailed('未通过验证')
class Mypermissions(BasePermission):
def has_permission(self, request, view):
try:
if request.user.user_type != 0:
return 'success'
else:
return False
except AttributeError:
raise exceptions.AuthenticationFailed('未通过验证')
class Mythrottling(SimpleRateThrottle):
scope = 'uuu'
# 'DEFAULT_THROTTLE_RATES': {
# 'xxx': '10/day'
# }
def get_cache_key(self, request, view):
return request.META.get('REMOTE_ADDR')
视图层
from django.shortcuts import render
# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from app.models import *
from app.Myserize import BookSerializers,PublishSerializers
from rest_framework.viewsets import ModelViewSet,ViewSetMixin
from django_redis import get_redis_connection
import pickle
from app.Myauth import *
class Books(ViewSetMixin,APIView):
# queryset=Book.objects.all()
# serializer_class=BookSerializers
authentication_classes = []
permission_classes = []
def post(self,request):
book_ret=Book.objects.all()
response={'statue': 1, 'msg': '获取成功'}
response['data']=BookSerializers(book_ret,many=True).data
return Response(response)
class Publishs(ViewSetMixin,APIView):
def post(self,request):
response = {'statue': 1, 'msg': '新增成功'}
print(request.data)
model=PublishSerializers(data=request.data)
if model.is_valid():
model.save()
response['data']=model.data
else:
response['data']=model.errors
return Response(response)
class Login(ViewSetMixin,APIView):
authentication_classes = []
permission_classes = []
def post(self,request):
name=request.data.get('name',None)
pwd=request.data.get('pwd',None)
user=User.objects.filter(name=name,pwd=pwd).first()
if user:
request.user=user
conn=get_redis_connection()
response = {'statue': 1, 'msg': '登陆成功'}
token=pickle.dumps(str(user.id))
conn.set('token',token)
conn.expire('token',20)
response['date']=user.id
return Response(response)
return render(request,'login.html')
def get(self,request):
return render(request, 'login.html')