framework —— auth认证
1.目录结构
2.urls.py
from django.conf.urls import url from django.contrib import admin from app02 import views as app02_view urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^hosts/‘,app02_view.HostView.as_view()), url(r‘^auth/$‘,app02_view.AuthView.as_view()) ]
3.models.py
from django.db import models # Create your models here. class Userinfo(models.Model): username = models.CharField(max_length=32) password = models.CharField(max_length=64) token = models.CharField(max_length=64,null=True)
4.views.py
from django.shortcuts import render,HttpResponse from rest_framework.views import APIView from rest_framework.request import Request from rest_framework.exceptions import APIException from rest_framework.response import Response import time import hashlib # Create your views here. from app02 import models # class MyAuthentication(object): # def authenticate(self,request): # token = request.query_params.get(‘token‘) # if token == ‘ASSDSA‘: # return (‘uuuuuuuuuuu‘,‘aaaaaaaaaaa‘) # raise APIException(‘认证失败‘) class AuthView(APIView): authentication_classes = [] def get(self,request): ‘‘‘ 接收用户名和密码 :param request: :return: ‘‘‘ ret ={"code":1000,"msg":None} user = request.query_params.get(‘user‘) pwd = request.query_params.get(‘pwd‘) user_obj = models.Userinfo.objects.filter(username=user,password=pwd).first() if not user_obj: ret[‘code‘] = 1001 ret[‘msg‘] = "用户名或密码错误" return Response(ret) #创建随机字符串 ctime = time.time() key = "%s|%s"%(user,pwd) m = hashlib.md5() m.update(key.encode(‘utf-8‘)) token = m.hexdigest() #保存到数据 user_obj.token = token user_obj.save() ret[‘token‘] = token return Response(ret) class HostView(APIView): def get(self,request,*args,**kwargs): self.dispatch print(request.user) print(request.auth) return Response(‘主机列表‘)
5.utils.py
from django.shortcuts import render,HttpResponse from rest_framework.views import APIView from rest_framework.request import Request from rest_framework.exceptions import APIException from rest_framework.response import Response from app02 import models class MyAuthentication(object): def authenticate(self,request): token = request.query_params.get(‘token‘) obj = models.Userinfo.objects.filter(token=token).first() if obj: return obj(obj.username,obj) raise APIException(‘用户认证认证失败‘)
6.settings.py
RESTFRAMEWORK = { ‘UNAUTHENTICATED_USER‘:None, ‘UNAUTHENTICATED_TOKEN‘:None, "DEFAULT_AUTHENTICATION_CLASSES":[ "app02.utils.MyAuthentication", ] }
原文地址:https://www.cnblogs.com/zhongbokun/p/8419021.html
时间: 2024-10-08 02:13:04