标签:ott ice scope setting lte api sea md5 rate
只有认证通过的用户才能访问指定的url地址,比如:查询课程信息,需要登录之后才能查看,没有登录,就不能查看,这时候需要用到认证组件
(1)models层:
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):
user=models.OneToOneField(to=‘User‘)
token=models.CharField(max_length=64)
(2)新建认证类(验证通过return两个参数)
from rest_framework.authentication import BaseAuthentication
class TokenAuth():
def authenticate(self, request):
token = request.GET.get(‘token‘)
token_obj = models.UserToken.objects.filter(token=token).first()
if token_obj:
return
else:
raise AuthenticationFailed(‘认证失败‘)
def authenticate_header(self,request):
pass
(3)view层
def get_random(name):
import hashlib
import time
md=hashlib.md5()
md.update(bytes(str(time.time()),encoding=‘utf-8‘))
md.update(bytes(name,encoding=‘utf-8‘))
return md.hexdigest()
class Login(APIView):
def post(self,reuquest):
back_msg={‘status‘:1001,‘msg‘:None}
try:
name=reuquest.data.get(‘name‘)
pwd=reuquest.data.get(‘pwd‘)
user=models.User.objects.filter(username=name,password=pwd).first()
if user:
token=get_random(name)
models.UserToken.objects.update_or_create(user=user,defaults={‘token‘:token})
back_msg[‘status‘]=‘1000‘
back_msg[‘msg‘]=‘登录成功‘
back_msg[‘token‘]=token
else:
back_msg[‘msg‘] = ‘用户名或密码错误‘
except Exception as e:
back_msg[‘msg‘]=str(e)
return Response(back_msg)
class Course(APIView):
authentication_classes = [TokenAuth, ]
def get(self, request):
return HttpResponse(‘get‘)
def post(self, request):
return HttpResponse(‘post‘)
在setting中
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",]
}
在views需要认证的类中
authentication_classes = [TokenAuth, ]
与认证类似
1 写一个类
class MyPermission():
def has_permission(self,request,view):
token=request.query_params.get(‘token‘)
ret=models.UserToken.objects.filter(token=token).first()
if ret.user.type==2:
# 超级用户可以访问
return True
else:
return False
2 局部使用:
permission_classes=[MyPermission,]
3 全局使用:
REST_FRAMEWORK={
‘DEFAULT_PERMISSION_CLASSES‘:[‘utils.common.MyPermission‘,]
}
与认证类似
1 写一个类:
from rest_framework.throttling import SimpleRateThrottle
class VisitThrottle(SimpleRateThrottle):
scope = ‘xxx‘
def get_cache_key(self, request, view):
return self.get_ident(request)
2 在setting里配置:
‘DEFAULT_THROTTLE_RATES‘:{
‘xxx‘:‘5/h‘,
}
3 局部使用
throttle_classes=[VisitThrottle,]
4 全局使用
REST_FRAMEWORK={
‘DEFAULT_THROTTLE_CLASSES‘:[‘utils.common.MyPermission‘,]
}
标签:ott ice scope setting lte api sea md5 rate
原文地址:https://www.cnblogs.com/luck-L/p/9839409.html