from rest_framework.authentication import BaseAuthenticationfrom rest_framework.permissions import BasePermissionfrom rest_framework.throttling import BaseThrottle,SimpleRateThrottlefrom django_redis import get_redis_connectionfrom rest_framework import exceptionsimport picklefrom app import modelsclass 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 Responsefrom rest_framework.views import APIViewfrom app.models import *from app.Myserize import BookSerializers,PublishSerializersfrom rest_framework.viewsets import ModelViewSet,ViewSetMixinfrom django_redis import get_redis_connectionimport picklefrom 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‘)
原文地址:https://www.cnblogs.com/wrqysrt/p/10660256.html
时间: 2024-10-05 12:26:44