认证权限频率自定义

Posted oldboyzzf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了认证权限频率自定义相关的知识,希望对你有一定的参考价值。

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‘)

以上是关于认证权限频率自定义的主要内容,如果未能解决你的问题,请参考以下文章

drf认证权限频率

drf-jwt认证组件权限组件频率组件的使用

79- drf三大认证的配置及使用方法

三大认证

自定义路由组件,Django的admin后台管理,DRF的三大认证,jwt认证

自定义频率认证