代码语言:javascript复制
rest_framework自定义认证,简单两步即可实现
下面是所有views urls models 的代码
代码语言:javascript复制#views.py
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.authentication import BasicAuthentication
from . import models
def md5(user):
'''生成md5随机字符串'''
import hashlib
import time
ctime=str(time.time())
m=hashlib.md5(bytes(user,encoding='utf-8'))
m.update(bytes(ctime,encoding='utf-8'))
return m.hexdigest()
ORDER_DICT={
1:{
'name':'狗头',
'age':'18',
'sex':'男',
'content':'.....'
},
2:{
'name':'毛毛',
'age':'99',
'sex':'女',
'content':'.....'
},
}
def index(request):
return HttpResponse('ok')
class AuthView(APIView):
'''
用于用户登录认证
'''
def post(self,request,*args,**kwargs):
ret={'code':1000,'msg':None}
try:
user=request._request.POST.get('username')
pwd=request._request.POST.get('password')
obj=models.UserInfo.objects.filter(username=user,password=pwd).first()
if obj:
ret['code']=1001
ret['msg']='登录成功'
# 创建token表
token=md5(user)
print(token)
# 创建或更新token
models.UserToken.objects.update_or_create(user=obj,defaults={'token':token})
ret['token']=token
else:
ret['code']=1004
ret['msg']='账号或密码错误'
except Exception as e:
ret['code'] = 1002
ret['msg'] = '请求异常'
return JsonResponse(ret)
class Authication(object):
'''自定义认证需要两步,第一步先写一个类,第二步在需要认证的地方应用上类就可以实现认证'''
# 主要认证逻辑
def authenticate(self,request):
from rest_framework import exceptions
token=request._request.GET.get('token')
token_obj=models.UserToken.objects.filter(token=token).first()
if not token_obj:
raise exceptions.AuthenticationFailed('用户认证失败')
return (token_obj.user,token_obj)
# 必写这个函数,
def authenticate_header(self,request):
pass
class OrderView(APIView):
# 自定义认证
# 自定义认证类添加进来即可实现认证
authentication_classes = [Authication]
def get(self,request,*args,**kwargs):
# request.user
# request.auth
ret = {'code': 1000, 'msg': None, 'data': None}
# token=request._request.GET.get('token')
# if not token:
# return JsonResponse({'code':1003,'msg':'用户未登录'})
try:
ret['data']=ORDER_DICT
except Exception as e:
pass
return JsonResponse(ret)
class UserInfoView(APIView):
authentication_classes = [Authication]
def get(self,request):
return HttpResponse('用户信息')
#urls.py
代码语言:javascript复制from django.urls import path
from . import views
app_name='app1'
urlpatterns=[
path('',views.index),
path('api/v1/auth',views.AuthView.as_view()),
path('api/v1/order',views.OrderView.as_view()),
path('api/v1/user',views.UserInfoView.as_view()),
]
#models.py
代码语言:javascript复制from django.db import models
class UserInfo(models.Model):
user_type_choices=(
(1,'普通用户'),
(2,'VIP'),
(3,'SIP'),
)
user_type=models.IntegerField(choices=user_type_choices,)
username=models.CharField(max_length=32,unique=True)
password=models.CharField(max_length=64)
class UserToken(models.Model):
user=models.OneToOneField(to='UserInfo',on_delete=models.CASCADE)
token=models.CharField(max_length=64)
# Create your models here.