定义个一个认证类
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication
class Authentication(BaseAuthentication): def authenticate(self,request): token=request._request.GET.get("token") token_obj=UserToken.objects.filter(token=token).first() if not token_obj: raise exceptions.AuthenticationFailed("验证失败!") return (token_obj.user,token_obj)
view配置登录后,访问其他url进行认证:
登录:
def get_random_str(user): import hashlib,time ctime=str(time.time()) md5=hashlib.md5(bytes(user,encoding="utf8")) md5.update(bytes(ctime,encoding="utf8")) return md5.hexdigest() from app01.service.auth import * from django.http import JsonResponse class LoginViewSet(APIView): authentication_classes = [Authentication,] def post(self,request,*args,**kwargs): res={"code":1000,"msg":None} try: user=request._request.POST.get("user") pwd=request._request.POST.get("pwd") user_obj=UserInfo.objects.filter(user=user,pwd=pwd).first() print(user,pwd,user_obj) if not user_obj: res["code"]=1001 res["msg"]="用户名或者密码错误" else: token=get_random_str(user) UserToken.objects.update_or_create(user=user_obj,defaults={"token":token}) res["token"]=token except Exception as e: res["code"]=1002 res["msg"]=e return JsonResponse(res,json_dumps_params={"ensure_ascii":False})
认证:
class BookView(APIView):
authentication_classes = [Authentication,] # [Authentication(),] 这写入认证累名字即可
# permission_classes = []
# throttle_classes = []
def get(self,request):
print("request.user",request.user)
print("request.auth",request.auth)
print("_request.body",request._request.body)
print("_request.GET",request._request.GET)
book_list=Book.objects.all()
以上是局部配置认证
全局配置:
settings.py配置如下:
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",] #这个代表认证类的位置
}
权限:
class SVIPPermission(object): message="只有超级用户才能访问" def has_permission(self,request,view): username=request.user user_type=User.objects.filter(name=username).first().user_type if user_type==3: return True # 通过权限认证 else: return False #不通过会获取上面message
这是全局配置:
setting 配置:
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": ["app01.utils.SVIPPermission",],
}
局部配置:
class BookView(APIView):
#authentication_classes = [Authentication,] # [Authentication(),] 这写入认证累名字即可
# permission_classes = [SVIPPermission] 这些写入局部配合的权限
# throttle_classes = []
def get(self,request):
print("request.user",request.user)
print("request.auth",request.auth)
print("_request.body",request._request.body)
print("_request.GET",request._request.GET)
book_list=Book.objects.all()